添加两个 pandas 数据框 [英] Adding two pandas dataframes
本文介绍了添加两个 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个dataframes
,都由timeseries
索引.我需要将元素加在一起以形成新的dataframe
,但前提是索引和列相同.如果该项目不存在于dataframe
之一中,则应将其视为零.
I have two dataframes
, both indexed by timeseries
. I need to add the elements together to form a new dataframe
, but only if the index and column are the same. If the item does not exist in one of the dataframe
s then it should be treated as a zero.
我尝试使用.add
,但是无论索引和列如何,这总和.还尝试了一个简单的combined_data = dataframe1 + dataframe2
,但是如果两个数据帧都没有该元素,则会给出一个NaN
.
I've tried using .add
but this sums regardless of index and column. Also tried a simple combined_data = dataframe1 + dataframe2
but this give a NaN
if both dataframes don't have the element.
有什么建议吗?
推荐答案
x.add(y, fill_value=0)
怎么样?
import pandas as pd
df1 = pd.DataFrame([(1,2),(3,4),(5,6)], columns=['a','b'])
Out:
a b
0 1 2
1 3 4
2 5 6
df2 = pd.DataFrame([(100,200),(300,400),(500,600)], columns=['a','b'])
Out:
a b
0 100 200
1 300 400
2 500 600
df_add = df1.add(df2, fill_value=0)
Out:
a b
0 101 202
1 303 404
2 505 606
这篇关于添加两个 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文