gpt4 book ai didi

python - 分组

转载 作者:行者123 更新时间:2023-11-28 22:25:16 26 4
gpt4 key购买 nike

大家好,我的数据框中有以下列:

     LC_REF
1 DT 16 2C
2 DT 16 2C
3 DT 16 2C

1 DT 16 3C
6 DT 16 3C
3 DT 16 3C
7 DT 16 3C

0 DT 17 1C
0 DT 17 1C
0 DT 17 1C
1 DT 17 1C

0 DT 17 2C
2 DT 17 2C
4 DT 17 2C
5 DT 17 2C

4 DT 17 3C
1 DT 17 3C
8 DT 17 3C

我想知道是否可以组织每组 LC_REF,使索引按升序排列:

     LC_REF
1 DT 16 2C
2 DT 16 2C
3 DT 16 2C

1 DT 16 3C
3 DT 16 3C
6 DT 16 3C
7 DT 16 3C

0 DT 17 1C
0 DT 17 1C
0 DT 17 1C
1 DT 17 1C

0 DT 17 2C
2 DT 17 2C
4 DT 17 2C
5 DT 17 2C

1 DT 17 3C
4 DT 17 3C
8 DT 17 3C

到目前为止我已经尝试过:

 df.groupby('LC_REF').apply(pd.DataFrame.sort_index,'LC_REF',1)
grouped = df.groupby('LC_REF').sum().reset_index()

但这并没有给出正确的输出。

最佳答案

我认为更好的方法是使用 reset_index对于 index 中的列,然后是 sort_values最后set_index :

df = df.reset_index().sort_values(['LC_REF','index']).set_index('index').rename_axis(None)
print (df)
LC_REF
1 DT 16 2C
2 DT 16 2C
3 DT 16 2C
1 DT 16 3C
3 DT 16 3C
6 DT 16 3C
7 DT 16 3C
0 DT 17 1C
0 DT 17 1C
0 DT 17 1C
1 DT 17 1C
0 DT 17 2C
2 DT 17 2C
4 DT 17 2C
5 DT 17 2C
1 DT 17 3C
4 DT 17 3C
8 DT 17 3C

关于python - 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45638738/

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