熊猫按任何给定列中的特定值分组

non*_*iam 5 python dataframe pandas pandas-groupby

鉴于熊猫数据框如下:

   Partner1 Partner2    Interactions
0  Ann      Alice       1
1  Alice    Kate        8
2  Kate     Tony        9
3  Tony     Ann         2
Run Code Online (Sandbox Code Playgroud)

我如何按特定合作伙伴分组,比如说找到安的互动总数?

就像是

gb = df.groupby(['Partner1'] or ['Partner2']).agg({'Interactions': 'sum'})
Run Code Online (Sandbox Code Playgroud)

并得到答案:

Partner Interactions
Ann     3
Alice   9
Kate    17
Tony    11
Run Code Online (Sandbox Code Playgroud)

YOL*_*OLO 0

您可以合并数据框本身:

# join the df to itself
join_df = df.merge(df, left_on='Partner1', right_on='Partner2', suffixes=('', '_'))

# get sum
join_df['InteractionsSum'] = join_df[['Interactions', 'Interactions_']].agg(sum, 1)

join_df = join_df[['Partner1', 'Interactions']].copy()

print(join_df)

  Partner1  Interactions
0      Ann             1
1    Alice             8
2     Kate             9
3     Tony             2
Run Code Online (Sandbox Code Playgroud)