上一篇pandas數組(pandas Series)-(3)向量化運算里說到,將兩個 pandas Series 進行向量化運算的時候,如果某個 key 索引只在其中一個 Series 里出現,計算的結果會是 NaN ,那么有什么辦法能處理 NaN 呢?
1. dropna() 方法:
此方法會把所有為 NaN 結果的值都丟棄,相當於只計算共有的 key 索引對應的值:
import pandas as pd s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']) s2 = pd.Series([10, 20, 30, 40], index=['c', 'd', 'e', 'f']) s3 = s1+s2 print(s3) # 結果: a NaN b NaN c 13.0 d 24.0 e NaN f NaN dtype: float64 print(s3.dropna()) # 結果: c 13.0 d 24.0 dtype: float64
2. fill_value 參數:
設置 fill_value參數可以給一個Series沒有key索引對應值的時候設置一個填充值:
s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']) s2 = pd.Series([10, 20, 30, 40], index=['c', 'd', 'e', 'f']) s3 = s1.add(s2, fill_value=0) print(s3) # 結果: a 1.0 b 2.0 c 13.0 d 24.0 e 30.0 f 40.0 dtype: float64
這樣, s2 里雖然沒有 'a','b' 這個索引 key , s1 里雖然沒有 'e','f' 這兩個 key ,但是在運算的時候,會用 0 去填充進行運算,也可以設置為其他值.
可見,以上這兩種方法的區別就在於,一個會除去兩個 Series 不共有的 key ,一個會用填充值去填補不共有的 key 的值.