【问题标题】:Way of summing all fields in rows with identical name in pandas df?在pandas df中对具有相同名称的行中的所有字段求和的方式?
【发布时间】: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()

标签: python pandas dataframe


【解决方案1】:

您可以尝试使用数据透视表吗?

pd.pivot_table(my_df, index="fusion", values=col_l, aggfunc=np.sum)

您还需要事先import numpy as np。 你得到一个如图所示的数据透视表:

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-25
  • 2016-08-25
  • 2021-11-12
  • 2022-09-30
  • 2022-01-09
相关资源
最近更新 更多