在两个不同列中的平均值

问题描述 投票:0回答:1

i具有如下所示的数据框。 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),但没有用。任何建议将不胜感激。

python pandas
1个回答
0
投票
# Add a (temporary) column with a sorted union of col_1 and col_2 df['sorted_keys'] = df[['col_1', 'col_2']].apply(lambda x: ''.join(sorted(x)), axis=1) # Then simply groupby it and average it out df.groupby(['sorted_keys']).mean()
© www.soinside.com 2019 - 2024. All rights reserved.