![](/img/trans.png)
[英]How to transform the result of a Pandas `GROUPBY` function to the original dataframe
[英]In Pandas, how to send the output from groupby transform to the original dataframe?
考慮下面的例子
import pandas as pd
import numpy as np
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'D' : np.random.randn(8)})
group=df.groupby(['A','B'])
agg_df=group.agg({'D':lambda x: x[x>0].sum(), 'D':lambda x: x[x<0].sum()} )
在這里,我想在原始數據幀df中獲得兩個其他變量。
一個是D中正元素的總和,另一個是D中負元素的總和。使用agg
是直接的,如您在上面的代碼中所看到的。
但是,我希望這些值在主數據框中針對對應於特定groupby
組合的每一行重復 。
天真的語法將使用:
transform_df=group.transform({'D':lambda x: x[x>0].sum(), 'D':lambda x: x[x<0].sum()} )
但是那是失敗的。 我在這里做錯了什么?
謝謝
如果用兩行表示,則邏輯將變得更易於讀寫
df['d_pos_sum'] = df.groupby(['A', 'B']).transform(lambda x: x[x>0].sum())
df['d_neg_sum'] = df.groupby(['A', 'B']).transform(lambda x: x[x<0].sum())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.