简体   繁体   English

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

[英]Pandas- merging two dataframe by sum the values of columns and index

I want to merge two datasets by indexes and columns.我想按索引和列合并两个数据集。

I want to merge entire dataset我想合并整个数据集

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

This was what I expected the output of df_sum这是我期望的 df_sum 输出

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

You can use : df1.add(df2, fill_value=0) .您可以使用: df1.add(df2, fill_value=0) It will add df2 into df1 also it will replace NAN value with 0 .它将df2添加到df1它还将用0替换NAN值。

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM