我有一个数据框,其中的值已分配给组:
import pandas as pd
df = pd.DataFrame({ 'num' : [0.43, 5.2, 1.3, 0.33, .74, .5, .2, .12],
'group' : [1, 2, 2, 2, 3,4,5,5]
})
df
group num
0 1 0.43
1 2 5.20
2 2 1.30
3 2 0.33
4 3 0.74
5 4 0.50
6 5 0.20
7 5 0.12
我想确保没有任何值(value)是单独存在的。如果某个值是“孤立”值,则应将其重新分配给具有多个成员的下一个最高组。因此,生成的数据框应如下所示:
group num
0 2 0.43
1 2 5.20
2 2 1.30
3 2 0.33
4 5 0.74
5 5 0.50
6 5 0.20
7 5 0.12
实现这个结果最Pythonic的方法是什么?
最佳答案
这是我找到的一个解决方案,可能有更好的方法来做到这一点......
# Find the orphans
count = df.group.value_counts().sort_index()
orphans = count[count == 1].index.values.tolist()
# Find the sets
sets = count[count > 1].index.values.tolist()
# Find where orphans should be remapped
where = [bisect.bisect(sets, x) for x in orphans]
remap = [sets[x] for x in where]
# Create a dictionary for remapping, and replace original values
change = dict(zip(orphans, remap))
df = df.replace({'group': change})
df
group num
0 2 0.43
1 2 5.20
2 2 1.30
3 2 0.33
4 5 0.74
5 5 0.50
6 5 0.20
7 5 0.12
关于python - 在 python pandas 中重新映射和重新分组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51536958/