pandas數組(pandas Series)-(3)向量化運算
阿新 • • 發佈:2018-06-23
索引 PE 4.0 bsp 進行 index索引 float dex 返回
這篇介紹下有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
pandas數組(pandas Series)-(3)向量化運算