python - 跨两个不同列的平均值
问题描述
我有一个如下所示的数据框。中的元素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 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
推荐阅读
- ios - Podfile.lock 版本和 pod [podfile] --版本号不同
- html - 在 Angular 中使用项目数组
- c# - 我正在使用 while 循环在 C# 中反转一个字符串我得到正确的输出但是我使用 for 循环的相同逻辑然后输出是错误的
- protractor - Visual Studio 中的 Protractor npm 安装(节点模块无法在 Visual Studio 中安装)
- python - Python嵌套/递归/树排序与熊猫
- amazon-web-services - Terraform route53 批量记录
- hibernate - 使用 @OneToOne 映射但外键不会使约束失败或不工作
- python - 在 Keras 中不断分配具有不同常量张量的变量时会发生什么?
- php - PHP Codeigniter Htaccess。删除控制器名称和 index.php 并重写 url
- javascript - 在回调中访问全局定义的变量?