gpt4 book ai didi

python - 在间隔列表上自定义 pandas groupby

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:49 25 4
gpt4 key购买 nike

我有一个数据框df:

     A    B
0 28 abc
1 29 def
2 30 hij
3 31 hij
4 32 abc
5 28 abc
6 28 abc
7 29 def
8 30 hij
9 28 abc
10 29 klm
11 30 nop
12 28 abc
13 29 xyz

df.dtypes

A object # A is a string column as well
B object
dtype: object

我想将此列表中的值用于 groupby:

i = np.array([ 3,  5,  6,  9, 12, 14])

基本上,df 中索引为 0、1、2 的所有行都在第一组中,索引为 3、4 的行在第二组中,索引为 5 的行在第三组中, 等等。

我的最终目标是:

A              B
28,29,30 abc,def,hij
31,32 hij,abc
28 abc
28,29,30 abc,def,hij
28,29,30 abc,klm,nop
28,29 abc,xyz

目前使用 groupby + pd.cut 的解决方案:

df.groupby(pd.cut(df.index, bins=np.append([0], i)), as_index=False).agg(','.join)

A B
0 29,30,31 def,hij,hij
1 32,28 abc,abc
2 28 abc
3 29,30,28 def,hij,abc
4 29,30,28 klm,nop,abc
5 29 xyz

结果不正确:-(

我怎样才能正确地做到这一点?

最佳答案

你非常接近,但是在 pd.cut 中使用 include_lowest=Trueright=False 因为你想要 0 垃圾箱中的第一个索引,然后您不想包含每个垃圾箱的最后一个元素,即

idx = pd.cut(df.index, bins=np.append([0], i), 
include_lowest=True, right=False)
df.groupby(idx, as_index=False).agg(','.join)
A              B28,29,30       abc,def,hij31,32          hij,abc28             abc28,29,30       abc,def,hij28,29,30       abc,klm,nop28,29          abc,xyz

关于python - 在间隔列表上自定义 pandas groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47304847/

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