user13412850
user13412850

Reputation: 519

python: how do I add two dataframes with different number of rows

Assuming there are two dataframes

df1 = pd.DataFrame([[8, 4],[9, 4],[1, 8]],columns=['A','B'])
df2 = pd.DataFrame([[7, 1],[3, 9],[9, 2],[8, 7],[5, 5],[3, 8]],columns=['A','B'])

if I add df1 and df2 I get something like this

        A     B
0  15.0   5.0
1  12.0  13.0
2  10.0  10.0
3   NaN   NaN
4   NaN   NaN
5   NaN   NaN

row 3 through 5 are NaN as df1 and df2 shapes differed.

Now, how do I get below as the output when I add df1 and df2?

       A     B
0  15.0   5.0
1  12.0  13.0
2  10.0  10.0
3   8.0   7.0
4   5.0   5.0
5   3.0   8.0

Upvotes: 1

Views: 55

Answers (1)

Tom
Tom

Reputation: 889

I assume you are using +. Try add instead, where you can supply the fill_value.

df1.add(df2, fill_value=0)

which gives

      A     B
0  15.0   5.0
1  12.0  13.0
2  10.0  10.0
3   8.0   7.0
4   5.0   5.0
5   3.0   8.0

Upvotes: 2

Related Questions