【发布时间】:2023-02-26 16:01:52
【问题描述】:
考虑以下DataFrame:
df = pd.DataFrame({'c0':['1980']*3+['1990']*2+['2000']*3,
'c1':['x','y','z']+['x','y']+['x','y','z'],
'c2':range(8) })
c0 c1 c2
0 1980 x 0
1 1980 y 1
2 1980 z 2
3 1990 x 3
4 1990 y 4
5 2000 x 5
6 2000 y 6
7 2000 z 7
我想使用 pandas 的 groupby 而不是 c0 来执行以下操作:
- 根据
c0(注明年份)对行进行分组。 - 在每组中,从
c2的值中减去y(在c1中)的c2的值。 - 添加一个新列
c3收集这些值。最后的结果是
c0 c1 c2 c3 0 1980 x 0 -1 1 1980 y 1 0 2 1980 z 2 1 3 1990 x 3 -1 4 1990 y 4 0 5 2000 x 5 -1 6 2000 y 6 0 7 2000 z 7 1我能够在没有
groupby的情况下得到结果,如下所示:dic = {} for yr in df['c0'].unique(): cond1 = ( df['c0']==yr ) tmp = df.loc[cond1,:].copy() cond2 = ( tmp['c1']=='y' ) val = tmp.loc[cond2,'c2'].to_numpy() tmp['c3'] = tmp['c2'] - val dic[yr] = tmp pd.concat([dic['1980'],dic['1990'],dic['2000']])它有效但看起来不太好。我试过
transform和apply为groupby,但无法弄清楚。任何帮助,将不胜感激。
【问题讨论】:
标签: python pandas dataframe group-by