i具有如下所示的数据框。 col_1
中的元素连接到col_2
中的元素,在output
中给出结果。另一方面,col_2
中的某些元素也位于col_1
中。例如:a-->b= 3
和b-->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)
,但没有用。任何建议将不胜感激。
# 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()