pandas數組(pandas Series)-(3)向量化運算


這篇介紹下有index索引的pandas Series是如何進行向量化運算的:

1. index索引數組相同:

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

直接把各個索引對應的值進行相加

 

2. index索引數組值相同,順序不同:

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

把各個索引對應的值相加,順序以第一個Series的為准

 

3. index索引數組某些值相同,某些值不相同:

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

相同索引值對應的值相加,不相同的因為找不到,所以返回NaN

 

4. index索引數組完全不同:

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

因為沒有相同的索引,所以無法對Series進行相加,得到的都是NaN

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM