python - 查找具有匹配列名的列的平均值
问题描述
我有一个类似于以下但有数千行和列的数据框:
x y ghb_00hr_rep1 ghb_00hr_rep2 ghb_00hr_rep3 ghl_06hr_rep1 ghl_06hr_rep2
x y 2 3 2 1 3
x y 5 7 6 2 1
我希望我的输出看起来像这样:
ghb_00hr hl_06hr
2.3 2
6 1.5
我的目标是找到匹配列的平均值。我想出了这个:temp = df.groupby(name, axis=1).agg('mean')
但我不确定如何将“名称”定义为匹配列。
我之前的策略如下:
name = pd.Series(['_'.join(i.split('_')[:-1])
for i in df.columns[3:]],
index = df.columns[3:]
)
temp = df.groupby(name, axis=1).agg('mean')
avg = pd.concat([df.iloc[:, :3], temp],
axis=1
)
但是,“复制”的数量范围为 1-4,因此按索引位置分组不是一种选择。
不确定是否有更好的方法可以做到这一点,或者我是否走在正确的轨道上。
解决方案
一个选项是 groupby level=0
:
(df.set_index(['name','x','y'])
.groupby(level=0, axis=1)
.mean().reset_index()
)
输出:
name x y ghb_00hr ghl_06hr
0 gene1 x y 2.333333 2.0
1 gene2 x y 6.000000 1.5
更新:对于修改后的问题:
d = df.filter(like='gh')
# or d = df.iloc[:, 2:]
# depending on your columns of interest
names = d.columns.str.rsplit('_', n=1).str[0]
d.groupby(names, axis=1).mean()
输出:
ghb_00hr ghl_06hr
0 2.333333 2.0
1 6.000000 1.5
推荐阅读
- google-compute-engine - Google Compute 虚拟机上的 IPSec 隧道
- javascript - Aurelia/Karma/Istanbul 无法读取未定义的属性“skip”和“decl”,但会产生融洽的关系
- apache-nifi - Apache NiFi:使用映射值将列添加到 csv
- r - 如何rbind(连接)存储为列表元素的数据帧
- arrays - 如何不在列表飞镖中重复相同的项目?
- javascript - 更新从 js 文件加载的对象中的属性 - javascript
- linux - Docker 加载代理环境变量失败
- angular - Angular Material Spinner 未显示,但存在于 DOM 中
- angular - 一些node_modules在本地有角度后没有推入git
- spring - 如何使用spring Data JPA将实体映射为java.util.Map?