gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:06:11 26 4
gpt4 key购买 nike

给定一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com