如何从多个数据框中添加多个列,同时在 Python 中保持标识列不变?
How to add multiple columns from multiple dataframes while keeping an identifying column constant in Python?
我有几个数据框
a, b, c, d, e
具有相同的列名 person_id, place_x, place_y, place_z
如何仅对 place_x place_y place_z
列的不同数据帧的所有值求和?
最终的数据框,像这样:
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
我怎样才能阻止这种情况发生?
另外,有没有办法简化这个,这样我就可以把所有需要的都加在一句话里?而不是多次添加?
将 concat
与聚合一起使用 sum
:
dfs = [a,b,c,d,e]
df = pd.concat(dfs).groupby('person_id', as_index=False).sum()
我有几个数据框
a, b, c, d, e
具有相同的列名 person_id, place_x, place_y, place_z
如何仅对 place_x place_y place_z
列的不同数据帧的所有值求和?
最终的数据框,像这样:
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
我怎样才能阻止这种情况发生?
另外,有没有办法简化这个,这样我就可以把所有需要的都加在一句话里?而不是多次添加?
将 concat
与聚合一起使用 sum
:
dfs = [a,b,c,d,e]
df = pd.concat(dfs).groupby('person_id', as_index=False).sum()