【问题标题】:How to add multiple columns from multiple dataframes while keeping an identifying column constant in Python?如何从多个数据框中添加多个列,同时在 Python 中保持标识列不变?
【发布时间】:2020-03-12 06:58:52
【问题描述】:

我有几个数据框 a, b, c, d, e 具有相同的列名person_id, place_x, place_y, place_z

如何仅对 place_x place_y place_zcolumns 汇总不同数据帧的所有值?

一个最终的数据框,像这样:

person_id     place_x       

001           a[place_x] +... e[place_x] 

我试过了

a=a.set_index('person_id')
b=b.set_index('person_id')
df_sum = a.add(b, fill_value=0)
c=set_index('person_id') 
df_sum = df_sum.add(c,fill_value=0)
// and so on until e

每列中的值被正确相加。但是 person_id 也是如此,例如,变为 001001 而不仅仅是 001 我怎样才能阻止这种情况发生?

另外,有没有办法简化这一点,以便我可以在一个句子中添加所有需要的内容?而不是多次添加?

【问题讨论】:

    标签: python pandas dataframe sum add


    【解决方案1】:

    concat 与聚合sum 一起使用:

    dfs = [a,b,c,d,e]
    df = pd.concat(dfs).groupby('person_id', as_index=False).sum()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多