Pandas Series的运算原来这么简单

Series的运算主要包括加法、减法、乘法和除法等基本算术运算。这些运算通常是按照索引对应计算的,如果两个Series的索引不同,则结果中对应位置将填充为NaN(空值)。

需要注意的是,在进行Series运算时,需要确保两个Series的索引是可对齐的,否则可能会导致意外的结果。如果两个Series的索引不同,可以使用Pandas的reindex()方法或align()方法来进行索引对齐。

1.Series基本算术运算

  • 适用于 NumPy 的数组运算也适用于 Series

# 导包
import pandas as pd

s = pd.Series(np.random.randint(10,100,size=10))
s
# 执行结果
0    11
1    40
2    25
3    83
4    18
5    42
6    84
7    43
8    30
9    75
dtype: int32

# 加法运算
s + 100
# 执行结果
0    111
1    140
2    125
3    183
4    118
5    142
6    184
7    143
8    130
9    175
dtype: int32

# 减法运算
s - 100
# 执行结果
0   -89
1   -60
2   -75
3   -17
4   -82
5   -58
6   -16
7   -57
8   -70
9   -25
dtype: int32

# 乘法运算
s * 100
# 执行结果
0    1100
1    4000
2    2500
3    8300
4    1800
5    4200
6    8400
7    4300
8    3000
9    7500
dtype: int32

# 除法运算
s / 100
# 执行结果
0    0.11
1    0.40
2    0.25
3    0.83
4    0.18
5    0.42
6    0.84
7    0.43
8    0.30
9    0.75
dtype: float64

# 取整运算
s // 100
# 执行结果
0    0
1    0
2    0
3    0
4    0
5    0
6    0
7    0
8    0
9    0
dtype: int32

# 次方运算
s ** 2
# 执行结果
0     121
1    1600
2     625
3    6889
4     324
5    1764
6    7056
7    1849
8     900
9    5625
dtype: int32

# 求余运算
s % 2
# 执行结果
0    1
1    0
2    1
3    1
4    0
5    0
6    0
7    1
8    0
9    1
dtype: int32

2.Series之间的运算

  • 在运算中自动对齐索引

  • 如果索引不对应,则补 NaN

  • Series 没有广播机制


# 创建两个长度一样的数据
s1 = pd.Series(np.random.randint(10,100,size=3))
s2 = pd.Series(np.random.randint(10,100,size=3))
display(s1,s2)
# 执行结果
0    56
1    74
2    69
dtype: int32
0    27
1    90
2    35
dtype: int32

# 对应元素数据相加
s1 + s2
# 执行结果
0     83
1    164
2    104
dtype: int32

# 对应元素数据相减
s1 - s2
# 执行结果
0    29
1   -16
2    34
dtype: int32

# 创建两个不同长度的数据
s3 = pd.Series(np.random.randint(10,100,size=3))
s4 = pd.Series(np.random.randint(10,100,size=4))
display(s3,s4)
# 执行结果
0    77
1    11
2    76
dtype: int32
0    18
1    74
2    20
3    93
dtype: int32

# 根据索引对应的值运算,索引不对应则补 NaN
s3 + s4
# 执行结果
0    95.0
1    85.0
2    96.0
3     NaN
dtype: float64
  • 注意:要想保留所有的 index,则需要使用 .add() 函数


display(s3,s4)
# 执行结果
0    77
1    11
2    76
dtype: int32
0    18
1    74
2    20
3    93
dtype: int32

# s3默认填充索引3的值为0
s3.add(s4,fill_value=0)
# 执行结果
0    95.0
1    85.0
2    96.0
3    93.0
dtype: float64

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

腾飞开源

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

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

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

打赏作者

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

抵扣说明:

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

余额充值