gpt4 book ai didi

python - pandas groupby 删除多个索引

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

我有一个数据框,其中有一列我想按列值分组并排序。 groupby后发现有多个索引,其中一个是origin dataframe的索引,我想删除这个索引。

示例数据框:

> d = pd.DataFrame(np.array([[0, 0, 1, 1, 2, 2, 2],
[3, 4, 5, 6, 7, 8, 9],
[1.25, 10.1, 2.3, 2.4, 1.2, 5.5, 5.7]]).T,
columns=['a', 'b', 'c'])

> d
a b c
0 0.0 3.0 1.25
1 0.0 4.0 10.10
2 1.0 5.0 2.30
3 1.0 6.0 2.40
4 2.0 7.0 1.20
5 2.0 8.0 5.50
6 2.0 9.0 5.70

我要申请的功能:

def top_all(df,column='b'):
return df.sort_index(by=column,ascending=True)

我如何使用 groupby:

d.groupby('a').apply(top_all)

我得到的结果:

        a   b   c
a
0.0 0 0.0 3.0 1.25
1 0.0 4.0 10.10
1.0 2 1.0 5.0 2.30
3 1.0 6.0 2.40
2.0 4 2.0 7.0 1.20
5 2.0 8.0 5.50
6 2.0 9.0 5.70

我想得到这样的结果:

        a   b   c
a
0.0 0.0 3.0 1.25
0.0 4.0 10.10
1.0 1.0 5.0 2.30
1.0 6.0 2.40
2.0 2.0 7.0 1.20
2.0 8.0 5.50
2.0 9.0 5.70

更新:

我尝试了带级别的reset_index,但结果不包含级别。我想要的结果是 groupby 格式,这意味着 a 列的值应该在 index.html 的不同组中拆分。不知道我说清楚没有...

> d.groupby('a').apply(top_all).reset_index(level=1, drop=True)
> d
a b c
a
0.0 0.0 3.0 1.25
0.0 0.0 4.0 10.10
1.0 1.0 5.0 2.30
1.0 1.0 6.0 2.40
2.0 2.0 7.0 1.20
2.0 2.0 8.0 5.50
2.0 2.0 9.0 5.70

最佳答案

要完成此任务,我唯一能想到的就是使用 openpyxl。首先使用 pandas 将输出保存到具有多索引的 excel,然后使用 openpyxl 删除列以保持您正在寻找的格式。

# export multi-index DataFrame to excel
d.groupby('a').apply(top_all).to_excel('python/test.xlsx')

import openpyxl
# open xlsx doc
book = openpyxl.load_workbook('python/test.xlsx')
# use active sheet
sheet = book.active
# delete col
sheet.delete_cols(2)
#save book
book.save('python/test.xlsx')

enter image description here

如果您不想在 excel 中显示索引名称(您当前将有重复的列:'a'):

group = d.groupby('a').apply(top_all)
group.index.names = [None, None] # set index names to None
group.to_excel('python/test.xlsx')

# open xlsx doc
book = openpyxl.load_workbook('python/test.xlsx')
# use active sheet
sheet = book.active
# delete col
sheet.delete_cols(2)
#save book
book.save('python/test.xlsx')

enter image description here

关于python - pandas groupby 删除多个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59525252/

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