首页 > 解决方案 > 跨两个不同列的平均值

问题描述

我有一个如下所示的数据框。中的元素col_1与 中的元素相连col_2,给出 中的结果output。另一方面,其中的一些元素col_2也在其中col_1。例如:a-->b= 3b-->a= 24

col_1   col_2   output      average
a        b       3            13.5   (because a-->b=3 and b-->a=24)
a        c       5             3.5   (because a-->c=5 and c-->a=2)
a        d       3      
b        a       24     
b        c       12     
b        d       5      
c        a       2      
c        b       3      
c        d       5

我需要的是计算这两个值的平均值,当然还有整个数据帧中的所有类似情况。

您可以将数据视为如下:col_1 中的人正在调用 col_2 中的人。输出是持续时间。我想计算每对人之间的平均持续时间

我试过使用pd.merge(df.col_1, df.col_2)但没有用。任何建议将不胜感激。

标签: pythonpandas

解决方案


这是实现此目的的一种方法,尽管我可能对您故意过度简化的示例阅读过多。

# Add a (temporary) column with the union of col_1 and col_2 
df['uniques'] = df[['col_1', 'col_2']].apply(np.unique, axis=1).astype(str) 


# Then simply groupby it and average it out 
df['mean'] = df.groupby(['uniques']).transform(np.mean)   

输出:

  col_1 col_2  output    uniques  mean
0     a     b       3  ['a' 'b']  13.5
1     a     c       5  ['a' 'c']   3.5
2     a     d       3  ['a' 'd']   3.0
3     b     a      24  ['a' 'b']  13.5
4     b     c      12  ['b' 'c']   7.5
5     b     d       5  ['b' 'd']   5.0
6     c     a       2  ['a' 'c']   3.5
7     c     b       3  ['b' 'c']   7.5
8     c     d       5  ['c' 'd']   5.0

推荐阅读