Pandas:Series和DataFrame间的算术元素

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

一、Series与Series

s1 = Series([1,3,5,7],index=['a','b','c','d'])
s2 = Series([2,4,6,8],index=['a','b','c','e'])
索引对齐项相加,不对齐项的值取NaN
s1+s2
a     3.0
b     7.0
c    11.0
d     NaN
e     NaN
dtype: float64

二、DataFrame与DataFrame

data1 = {'水果':['苹果','梨','草莓'],
       '数量':[3,2,5],
       '价格':[10,9,8]}
data2 = {'数量':[3,2,5,6],
        '价格':[10,9,8,7]}
df1 = DataFrame(data1)
df2 = DataFrame(data2)
在行和列上同时对齐后进行计算,如果找不到对应项则取NaN
print(df1*df2)
      价格    数量   水果
0  100.0   9.0  NaN
1   81.0   4.0  NaN
2   64.0  25.0  NaN
3    NaN   NaN  NaN

三、Series与DataFrame

1.利用广播实现DataFrame与某行的运算

print(df2+df2.iloc[0]) # 将第0行加到所有行上
   价格  数量
0  20   6
1  19   5
2  18   8
3  17   9

2.利用广播实现DataFrame与某列的运算(指定轴axis=0)

print(df2.sub(df2.iloc[:,0],axis=0))
   价格  数量
0   0  -7
1   0  -7
2   0  -3
3   0  -1

3.运算时如果无法对齐,则填充NaN

s = Series([1,1,1],index=['数量','价格','重量'])
print(df2+s)
   价格  数量  重量
0  11   4 NaN
1  10   3 NaN
2   9   6 NaN
3   8   7 NaN
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BQW_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值