问题
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?
回答1:
Either of these work:
df['a'] = df['a'] - df2['gamma']
df['b'] = df['b'] - df2['gamma']
-
df.sub(df2.iloc[:,0],axis=0)
来源:https://stackoverflow.com/questions/45227930/subtraction-of-pandas-dataframes