3 回答

TA貢獻1780條經(jīng)驗 獲得超1個贊
你可以試試這個,
DF.groupby('id').agg(agg1=('col1',lambda x:x[DF.loc[x.index,'col2'].idxmax()]),
agg2 = ('col2',lambda x:x[DF.loc[x.index,'col3'].idxmin()]),
agg3 = ('col1',lambda x:x[DF.loc[x.index,'col3'].idxmax()]))
agg1 agg2 agg3
id
1 5 4 3
2 5 3 5
3 7 4 7

TA貢獻1810條經(jīng)驗 獲得超5個贊
玩弄這個問題,主要是為了看看我是否可以提高原始解決方案的速度。這比命名聚合更快。
grp = df.groupby("id")
pd.DataFrame({ "col1": df.col1[grp.col2.idxmax()].array,
"col2": df.col2[grp.col3.idxmin()].array,
"col3": df.col1[grp.col3.idxmax()].array},
index=grp.indices)
col1 col2 col3
1 5 4 3
2 5 3 5
3 7 4 7
加速~3x。

TA貢獻1812條經(jīng)驗 獲得超5個贊
tidyversepython中的一種方式怎么樣:
>>> from datar.all import f, tibble, group_by, which_max, which_min, summarise
>>>
>>> DF = tibble(
... id=[1,1,1,2,2,2,2,3,3,3],
... col1=[1,3,5,2,5,3,6,3,67,7],
... col2=[4,6,8,3,65,3,5,4,4,7],
... col3=[34,64,53,5,6,2,4,6,4,67]
... )
>>>
>>> DF >> group_by(f.id) >> summarise(
... agg1=f.col1[which_max(f.col2)],
... agg2=f.col2[which_min(f.col3)],
... agg3=f.col1[which_max(f.col3)]
... )
id agg1 agg2 agg3
<int64> <int64> <int64> <int64>
0 1 5 4 3
1 2 5 3 5
2 3 7 4 7
我是datar
包的作者。如果您有任何問題,請隨時提交問題。
添加回答
舉報