使用以下代码:
import pandas as pd
df = pd.DataFrame({'ProbeGenes' : ['1431492_at Lipn', '1448678_at Fam118a','1452580_a_at Mrpl21'],
'(5)foo.ID.LN.x1' : [20.3, 25.3,3.1],
'(5)foo.ID.LN.x2' : [130, 150,173],
'(5)foo.ID.LN.x3' : [1.0, 2.0,12.0],
'(3)bar.ID.LN.x1' : [1,2,3],
'(3)bar.ID.LN.x2' : [4,5,6],
'(3)bar.ID.LN.x3' : [7,8,9]
})
new_cols = df.pop("ProbeGenes").str.split().apply(pd.Series)
new_cols.columns = ["Probe","Gene"]
df = df.join(new_cols)
cols = df.columns.tolist()
cols = cols[-2:] + cols[:-2]
df = df[cols]
df
我可以制作以下数据框:
Probe Gene (5)bar.ID.LN.x1 (5)bar.ID.LN.x2 (5)bar.ID.LN.x3 \
0 1431492_at Lipn 1 4 7
1 1448678_at Fam118a 2 5 8
2 1452580_a_at Mrpl21 3 6 9
(3)foo.ID.LN.x1 (3)foo.ID.LN.x2 (3)foo.ID.LN.x3
0 20.3 130 1
1 25.3 150 2
2 3.1 173 12
请注意,数据框包含两个 block (名为 foo
和 bar
),每个 block 依次包含 x1,x2,x3
。我想要做的是总结每个 block 中的值,从而产生这个数据框:
Probe Gene foo bar
1431492_at Lipn 151.3 12
1448678_at Fam118a 177.3 15
1452580_a_at Mrpl21 188.1 18
实际数据可以包含两个以上的 block 名。每个 block 将包含 2 或 3 个成员(x1,x2
或 x1,x2,x3
)。
可以使用以下正则表达式捕获 block 名称 /\(\d+\)(\w+)\..*/
我怎样才能做到这一点?
最佳答案
数据量小的一种选择
df['foo'] = df.filter(regex='foo').sum(axis=1) # It will filter all the columns which has the word 'foo' in it
df['bar'] = df.filter(regex='bar').sum(axis=1)
如果您的数据大小超过 10,000 行,请不要使用它。总的来说使用 axis=1
很慢
关于python - 在 Pandas 数据框中汇总列 block - 按行方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30090889/