pandas Series索引对齐与数值相加详解

Leo
Leo
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍pandas中Series对象通过加法运算符进行数值相加时的索引对齐机制。当两个Series索引完全一致、顺序不同、存在部分重叠或完全无交集时,相加结果如何生成。重点说明NaN值的产生逻辑及数据类型变化,帮助开发者理解pandas自动对齐特性。

具体实现方式如下所示:

 s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
 s2 = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])
 print s1 + s2
a 11
b 22
c 33
d 44
dtype: int64
 s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
 s2 = pd.Series([10, 20, 30, 40], index=['b', 'd', 'a', 'c'])
 print s1 + s2
a 31
b 12
c 43
d 24
dtype: int64
 s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
 s2 = pd.Series([10, 20, 30, 40], index=['c', 'd', 'e', 'f'])
 print s1 + s2
a  NaN
b  NaN
c 13.0
d 24.0
e  NaN
f  NaN
dtype: float64
 s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
 s2 = pd.Series([10, 20, 30, 40], index=['e', 'f', 'g', 'h'])
 print s1 + s2
a NaN
b NaN
c NaN
d NaN
e NaN
f NaN
g NaN
h NaN
dtype: float64

以上关于pandas中Series按索引相加的操作方法就是本文分享的全部内容,希望能为读者提供有价值的参考,同时也欢迎继续支持本站获取更多技术内容。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表