Subtraction of pandas dataframes

烂漫一生 提交于 2021-01-28 07:22:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!