查找具有匹配列名的列的平均值
Find the mean of columns with matching column names
我有一个类似于以下但有数千行和列的数据框:
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' 定义为匹配列。
我之前的策略如下:
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
)
但是 'replicates' 的数量在 1-4 之间,因此不能按索引位置分组。
不确定是否有更好的方法或者我是否在正确的轨道上。
您可以将 df.columns
转换为设置然后迭代:
df = pd.DataFrame([[1, 2, 3, 4, 5, 6]], columns=['a', 'a', 'a', 'b', 'b', 'b'])
for column in set(df.columns):
print(column, df[common_name].mean(axis=1))
将输出
a 0 2.0
dtype: float64
b 0 5.0
dtype: float64
如果顺序很重要,请使用 sorted
:
for column in sorted(set(df.columns)):
从这里您可以获得几乎任何您想要的格式的输出。
一个选项是分组 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
我有一个类似于以下但有数千行和列的数据框:
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' 定义为匹配列。
我之前的策略如下:
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
)
但是 'replicates' 的数量在 1-4 之间,因此不能按索引位置分组。
不确定是否有更好的方法或者我是否在正确的轨道上。
您可以将 df.columns
转换为设置然后迭代:
df = pd.DataFrame([[1, 2, 3, 4, 5, 6]], columns=['a', 'a', 'a', 'b', 'b', 'b'])
for column in set(df.columns):
print(column, df[common_name].mean(axis=1))
将输出
a 0 2.0
dtype: float64
b 0 5.0
dtype: float64
如果顺序很重要,请使用 sorted
:
for column in sorted(set(df.columns)):
从这里您可以获得几乎任何您想要的格式的输出。
一个选项是分组 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