Francesca
Francesca

Reputation: 13

Subtraction of pandas dataframes

I am trying to substract two pandas dataframes from each other, but get only NaN results:

Dataframe 1:
   alpha  beta
0      1     4
1      2     5
2      3     6

Dataframe 2:
   gamma
0      7
1      8
2      9

Dataframe operation:

df3=df1-df2

Result:

alpha  beta  gamma
0    NaN   NaN    NaN
1    NaN   NaN    NaN
2    NaN   NaN    NaN

However, if I convert everything to numpy matrices, it works:

Matrix operation:

matrix3=df1.as_matrix(['alpha','beta'])-df2.as_matrix(['gamma'])

Result:

[[-6 -3]
[-6 -3]
[-6 -3]]

How can I make this work with pandas?

Upvotes: 1

Views: 3703

Answers (1)

Ho Man
Ho Man

Reputation: 2345

Either of these work:

df['a'] = df['a'] - df2['gamma']
df['b'] = df['b'] - df2['gamma']

-

df.sub(df2.iloc[:,0],axis=0)

Upvotes: 4

Related Questions