pandas 可以輕鬆使用具有不同索引的物件,將物件相加時,如果有兩個索引不相同,那摩產生的索引將是兩個索引的聯集:
In [182]: s1 = pd.Series([7.3, -2.5, 3.4, 1.5], index=["a", "c", "d", "e"])
In [183]: s2 = pd.Series([-2.1, 3.6, -1.5, 4, 3.1],
index=["a", "c", "e", "f", "g"])
In [184]: s1
Out[184]:
a 7.3
c -2.5
d 3.4
e 1.5
dtype: float64
In [185]: s2
Out[185]:
a -2.1
c 3.6
e -1.5
f 4.0
g 3.1
dtype: float64
相加會產生:
In [186]: s1 + s2
Out[186]:
a 5.2
c 1.1
d NaN
e 0.0
f NaN
g NaN
dtype: float64
內部的資料對齊會在不重疊的標籤位置加入缺失值,這些缺失值會在後續的算術計算中傳播出去。
pandas 會將 DataFrame 的列與欄兩者對齊:
In [187]: df1 = pd.DataFrame(np.arange(9.).reshape((3, 3)), columns=list("bcd"),
index=["Ohio", "Texas", "Colorado"])
In [188]: df2 = pd.DataFrame(np.arange(12.).reshape((4, 3)), columns=list("bde"),
index=["Utah", "Ohio", "Texas", "Oregon"])
In [189]: df1
Out[189]:
b c d
Ohio 0.0 1.0 2.0
Texas 3.0 4.0 5.0
Colorado 6.0 7.0 8.0
In [190]: df2
Out[190]:
b d e
Utah 0.0 1.0 2.0
Ohio 3.0 4.0 5.0
Texas 6.0 7.0 8.0
Oregon 9.0 10.0 11.0
將兩者相加會得到一個 DataFrame,裡面的索引和欄是各個 DataFrame 裡的索引和欄的聯集:
In [191]: df1 + df2
Out[191]:
b c d e
Colorado NaN NaN NaN NaN
Ohio 3.0 NaN 6.0 NaN
Oregon NaN NaN NaN NaN
Texas 9.0 NaN 12.0 NaN
Utah NaN NaN NaN NaN
因為 c
與 e
這兩個欄位沒有同時出現在兩個 DataFrame 物件中,所以在結果中會是缺失值,當橫列的標籤沒有同時出現在兩個物件中也是如此。
將欄與列標籤都不相同的 DataFrame 物件相加,結果會為 null
:
In [192]: df1 = pd.DataFrame({"A": [1, 2]})
In [193]: df2 = pd.DataFrame({"B": [3, 4]})
In [194]: df1
Out[194]:
A
0 1
1 2
In [195]: df2
Out[195]:
B
0 3
1 4
In [196]: df1 + df2
Out[196]:
A B
0 NaN NaN
1 NaN NaN
今日的分享就到這囉,我們明天見,掰掰!