Pandas-通过对列和索引的值求和来合并两个数据框 [英] Pandas- merging two dataframe by sum the values of columns and index

查看:22
本文介绍了Pandas-通过对列和索引的值求和来合并两个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于Pandas-通过对列和索引的值求和来合并两个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆