gpt4 book ai didi

python - Pandas 中的两列分组

转载 作者:行者123 更新时间:2023-12-01 01:08:57 25 4
gpt4 key购买 nike

我有一个像这样的数据框:

df = pd.DataFrame({'sym': list('aabaabab'), 'dir':[0,0,0,1,0,1,1,1], 'price': [100, 101, 102, 110, 120, 125, 200, 250]})

dir price sym
0 0 100 a
1 0 101 a
2 0 102 b
3 1 110 a
4 0 120 a
5 1 125 b
6 1 200 a
7 1 250 b

我想对 sym 和一组 0 和 1 进行分组(不确定这是否是正确的术语!)。我想要的结果如下:

   dir  price sym
0 0 100 a
1 0 101 a
3 1 110 a
dir price sym
4 0 120 a
6 1 200 a
dir price sym
2 0 102 b
5 1 125 b
7 1 250 b

每次 sym 中的 dir 变为 0 时,我想要一个新的组,其中 0 之后有 1

最佳答案

使用cumsum创建另一个帮助键,然后groupby

df['helpkey']=df.groupby('sym').apply(lambda x : ((x['dir']==1)&(x['dir'].shift(-1)==0)).shift().fillna(0).cumsum()).reset_index(level=0,drop=True)
d={x: y for x , y in df.groupby(['helpkey','sym'])}
<小时/>
for x , y in df.groupby(['helpkey','sym']):
print(y)

sym dir price helpkey
0 a 0 100 0
1 a 0 101 0
3 a 1 110 0
sym dir price helpkey
2 b 0 102 0
5 b 1 125 0
7 b 1 250 0
sym dir price helpkey
4 a 0 120 1
6 a 1 200 1

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

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