【发布时间】:2021-08-19 17:08:23
【问题描述】:
我正用头撞墙: 我想为“融合”列中具有相同值的所有行逐行添加所有值。这是一个虚拟示例:
import pandas as pd
rows_l = [['AFF1_KMT2A', 3.0, 1.0, 1.0, 1.0, 4, 6.0],
['AFF1_KMT2A', 3.0, 2.0, 1.0, 0.0, 3, 6.0],
['TCF3_PBX1', 3.0, 1.0, 1.0, 0.0, 3, 5.0],
['TCF3_PBX1', 0.0, 0.0, 0.0, 1.0, 1, 1.0],
['ABL1_BCR', 1.0, 1.0, 1.0, 2.0, 4, 5.0]]
col_l = ['fusion', 'FusionCatcher', 'Manta', 'STARfusion', 'TopHat','tool_count', 'tot']
my_df = pd.DataFrame(rows_l, columns=col_l)
给我这个 my_df:
| fusion | FusionCatcher | Manta | STARfusion | TopHat | tool_count | tot | |
|---|---|---|---|---|---|---|---|
| 0 | ABL1_BCR | 1.0 | 1.0 | 1.0 | 2.0 | 4 | 5.0 |
| 1 | AFF1_KMT2A | 3.0 | 2.0 | 1.0 | 0.0 | 3 | 6.0 |
| 2 | TCF3_PBX1 | 3.0 | 1.0 | 1.0 | 0.0 | 3 | 5.0 |
| 3 | AFF1_KMT2A | 3.0 | 1.0 | 1.0 | 1.0 | 4 | 6.0 |
| 4 | TCF3_PBX1 | 0.0 | 0.0 | 0.0 | 1.0 | 1 | 1.0 |
当然,在我的真实文件中,相同的行并不总是相隔一行,而是无处不在...
我的输出应该是这样的:
| fusion | FusionCatcher | Manta | STARfusion | TopHat | tool_count | tot | |
|---|---|---|---|---|---|---|---|
| 0 | AFF1_KMT2A | 6.0 | 3.0 | 2.0 | 1.0 | 7 | 12.0 |
| 1 | TCF3_PBX1 | 3.0 | 1.0 | 1.0 | 1.0 | 4 | 6.0 |
| 2 | ABL1_BCR | 1.0 | 1.0 | 1.0 | 2.0 | 4 | 5.0 |
到目前为止,我只找到了 df['whatever_you_want_to_sum'].groupby(df['col_names_if_same_wil_be_bundled']),但这似乎只适用于 2 列,对我没有多大帮助。
是否有任何特定的python pandas 方法可以做到这一点,或者我应该继续写我的for-loops 直到打印看起来正确?
【问题讨论】:
-
my_df.groupby('fusion').sum()