python - 在 python pandas 中重新映射和重新分组值

标签 python pandas

我有一个数据框,其中的值已分配给组:

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/

相关文章:

php - 修改Held-Karp TSP算法,不需要回原点

python - Tornado :线程未在协程中使用 @run_on_executor 启动

python - 从python中的视频中获取特定的帧序列

python - 将数据框的列组合成新的数据框

python - Flask 消息在重定向中闪烁失败

python - 使用 hlines 创建甘特图?

python - 具有较小数据框随机列的大型数据框(Pandas)

python - 如何在 Pandas 中拆分列标题并正确导出到 Excel

python - Pandas Apply 函数无法始终如一地工作(Python 3)

python - 在每行的开头插入字符串