pandas算术运算

df1 = DataFrame(np.arange(12).reshape(3,4),columns=list('abcd'))
df1
Out[74]: 
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
df2 = DataFrame(np.arange(20).reshape(4,5),columns=list('abcde'))
df2
Out[79]: 
    a   b   c   d   e
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19

如果单纯相加的话,空值会返回NaN

df1+df2
Out[80]: 
      a     b     c     d   e
0   0.0   2.0   4.0   6.0 NaN
1   9.0  11.0  13.0  15.0 NaN
2  18.0  20.0  22.0  24.0 NaN
3   NaN   NaN   NaN   NaN NaN

所以需要使用df1的add方法,传入df2以及一个fill_value参数:

df1.add(df2,fill_value=0)
Out[83]: 
      a     b     c     d     e
0   0.0   2.0   4.0   6.0   4.0
1   9.0  11.0  13.0  15.0   9.0
2  18.0  20.0  22.0  24.0  14.0
3  15.0  16.0  17.0  18.0  19.0

df1.add(df2,fill_value=10)
Out[84]: 
      a     b     c     d     e
0   0.0   2.0   4.0   6.0  14.0
1   9.0  11.0  13.0  15.0  19.0
2  18.0  20.0  22.0  24.0  24.0
3  25.0  26.0  27.0  28.0  29.0
方法 说明
add 用于加法(+)的方法
sub 用于减法(-)的方法
div 用于除法(/)的方法
mul 用于乘法(*)的方法

Series和DataFrame之间的计算

df2
Out[122]: 
    a   b   c   d   e
z   0   1   2   3   4
x   5   6   7   8   9
c  10  11  12  13  14
v  15  16  17  18  19

series1 = df2.ix[0]
__main__:1: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/
indexing.html#ix-indexer-is-deprecated
series1
Out[136]: 
a    0
b    1
c    2
d    3
e    4
Name: (z,), dtype: int32df2-series1

df2-series1
Out[137]: 
    a   b   c   d   e
z   0   0   0   0   0
x   5   5   5   5   5
c  10  10  10  10  10
v  15  15  15  15  15

如果不是一一对应的话,同样会出现NaN
如果希望行在列上广播,必须用算术运算方法

series3=df2['d']
series3
Out[141]: 
z     3
x     8
c    13
v    18
Name: d, dtype: int32

df2.sub(series3,axis=0)
Out[145]: 
   a  b  c  d  e
z -3 -2 -1  0  1
x -3 -2 -1  0  1
c -3 -2 -1  0  1
v -3 -2 -1  0  1

猜你喜欢

转载自blog.csdn.net/weixin_43139613/article/details/82853984