pandas:算术运算,数据对齐

算术运算和数据对齐

在这里插入图片描述

from  pandas import  Index
from  pandas import Series,DataFrame
import  numpy as  np
import pandas as pd

#DataFrame算术:不重叠部分为NaN,重叠部分元素运算'
x=DataFrame(np.arange(9).reshape(3,3),
            columns=['A','B','C'],
            index=['a','b','c'])

y=DataFrame(np.arange(12).reshape((4,3)),
            columns=['A','B','C'],
            index=['a','b','c','d'])

print(x)
'''
   A  B  C
a  0  1  2
b  3  4  5
c  6  7  8
'''

print(y)
'''
   A   B   C
a  0   1   2
b  3   4   5
c  6   7   8
d  9  10  11
'''

print(x+y)
'''
      A     B     C
a   0.0   2.0   4.0
b   6.0   8.0  10.0
c  12.0  14.0  16.0
d   NaN   NaN   NaN
'''

#对x+y的不重叠部分填充,不是对结果NaN填充
print(x.add(y,fill_value = 0))  # x不变化
'''
      A     B     C
a   0.0   2.0   4.0
b   6.0   8.0  10.0
c  12.0  14.0  16.0
d   9.0  10.0  11.0
'''

#DataFrame与Series运算:每行/列进行运算
frame = DataFrame(np.arange(9).reshape((3, 3)),
                  columns = ['A','B','C'],
                  index = ['a', 'b', 'c'])
print(frame)
'''
   A  B  C
a  0  1  2
b  3  4  5
c  6  7  8
'''
series= frame.ix[0]
print(series)
'''
A    0
B    1
C    2
Name: a, dtype: int32
'''

print(frame-series)     # 默认按行运算
'''
   A  B  C
a  0  0  0
b  3  3  3
c  6  6  6
'''

series2 = Series(range(4), index = ['A','B','C','D'])
print(frame+series2)     # 按行运算:缺失列则为NaN
'''
   A  B   C   D
a  0  2   4 NaN
b  3  5   7 NaN
c  6  8  10 NaN
'''

series3 = frame.A
print(series3)
'''
a    0
b    3
c    6
Name: A, dtype: int32
'''

print( frame.sub(series3,axis = 0))    # 按列运算  ??(frame的行-series3)
'''
   A  B  C
a  0  1  2
b  0  1  2
c  0  1  2
'''

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值