减去pandas数据帧

时间:2017-07-21 02:14:47

标签: python pandas dataframe difference subtraction

我试图将两个pandas数据帧相互减去,但只获得NaN结果:

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

Dataframe 2:
   gamma
0      7
1      8
2      9

数据帧操作:

df3=df1-df2

结果:

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

但是,如果我将所有内容转换为numpy矩阵,它的工作原理如下:

矩阵操作:

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

结果:

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

如何使用pandas进行此操作?

1 个答案:

答案 0 :(得分:4)

其中任何一项工作:

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

-

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