python - 如何以特殊方式对 Pandas 数据框进行排序

标签 python pandas

给定一个 Pandas 数据框

df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8],
                   'b': [0,0,1,1,2,2,3,3]})

如何沿列排序 b以这样的方式将其重新排列为 {0,1,2,3,0,1,2,3} .

IE。结果数据帧是
1   0
3   1
5   2
7   3
2   0
4   1
6   2
8   3

最佳答案

使用 cumcount 添加一列

df.assign(x=df.groupby('b').cumcount()).sort_values(['x', 'b']).drop('x', axis=1)

   a  b
0  1  0
2  3  1
4  5  2
6  7  3
1  2  0
3  4  1
5  6  2
7  8  3

Numpy 的 lexsort , iloc , 和 cumcount
df.iloc[np.lexsort([df['b'], df.groupby('b').cumcount()])]

   a  b
0  1  0
2  3  1
4  5  2
6  7  3
1  2  0
3  4  1
5  6  2
7  8  3

关于python - 如何以特殊方式对 Pandas 数据框进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62072782/

相关文章:

python - django slugify - 定制德语变音符号

python - 抑制 pandas scatter_matrix 中的所有标签

pandas - 查询带有Period数据类型的数据帧时Jupyter内核崩溃

python - 对 Python pandas 数据框中的唯一值进行分组和计数

python - 在 Pandas 中将索引从整数更改为日期时出现问题

python - 适用于 Python 的亚马逊 API 库?

python - 即使我已经通过 pip 安装了 'flask_wtf' 和 'wtforms',但仍无法在虚拟环境中导入它们?

python - 如何查找列表中给定值的所有下限值和上限值

python - 如何在单个图中绘制多个seaborn.distplot

python - 按 Pandas 数据框分组并在每组中选择最新的