一、Series基本算术运算
- 适用于 NumPy 的数组运算也适用于 Series
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
二、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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...



