Pandas-通过对列和索引的值求和来合并两个数据框

2022-01-09 00:00:00 python pandas dataframe sum

问题描述

我想按索引和列合并两个数据集.

I want to merge two datasets by indexes and columns.

我想合并整个数据集

df1 = pd.DataFrame([[1, 0, 0], [0, 2, 0], [0, 0, 3]],columns=[1, 2, 3])
df1
    1   2   3
0   1   0   0
1   0   2   0
2   0   0   3

df2 = pd.DataFrame([[0, 0, 1], [0, 2, 0], [3, 0, 0]],columns=[1, 2, 3])
df2
    1   2   3
0   0   0   1
1   0   2   0
2   3   0   0

我已经尝试过这段代码,但我得到了这个错误.我不明白为什么它将轴的大小显示为错误.

I have tried this code but I got this error. I can't get why it shows the size of axis as an error.

df_sum = pd.concat([df1, df2])
       .groupby(df2.index)[df2.columns]
       .sum().reset_index()

ValueError: Grouper and axis must be same length

这就是我预期的 df_sum 的输出

This was what I expected the output of df_sum

df_sum
    1   2   3
0   1   0   1
1   0   4   0
2   3   0   3


解决方案

你可以使用:df1.add(df2, fill_value=0).它会将 df2 添加到 df1 中,并且它会将 NAN 值替换为 0.

You can use :df1.add(df2, fill_value=0). It will add df2 into df1 also it will replace NAN value with 0.

>>> import numpy as np
>>> import pandas as pd
>>> df2 = pd.DataFrame([(10,9),(8,4),(7,np.nan)], columns=['a','b'])
>>> df1 = pd.DataFrame([(1,2),(3,4),(5,6)], columns=['a','b'])
>>> df1.add(df2, fill_value=0)

    a     b
0  11  11.0
1  11   8.0
2  12   6.0

相关文章