如何處理 None 值來新增兩個 Pandas Series 物件?


在 Pandas Series 功能中,我們有一個名為 add() 的函式,用於將一個 Series 物件與另一個 Series 物件相加。它還可以用於將 Series 物件與整數和 Python 列表相加。

series.add() 方法有一個 fill_values 引數,用於透過將浮點值替換到該引數來有效地處理缺失值。預設情況下,該 fill_value 引數的輸入為 Nan。

示例

import pandas as pd
import numpy as np

sr1 = pd.Series(np.arange(1,6))
print('Series Object 1:',sr1, sep='
') sr2 = pd.Series(np.random.randint(10,20,4)) print('Series Object 2:',sr2, sep='
') result = sr1.add(sr2) print('Resultant series object with the addition of two Series:', result)

解釋

我們有兩個 Series 物件 sr1 和 sr2,它們分別使用 NumPy 的 arange 和 random 函式建立。sr1 物件有 5 個元素,sr2 只有 4 個元素。

這兩個 Series 物件的長度不同。我們使用 series.add() 函式將這兩個物件相加。

輸出

Series Object 1:
0   1
1   2
2   3
3   4
4   5
dtype: int32
Series Object 2:
0  15
1  12
2  16
3  12
dtype: int32
Resultant series object with addition of two Series: 0 16.0
1   14.0
2   19.0
3   16.0
4    NaN
dtype: float64

解釋

series.add() 函式的輸出可以在上面程式碼塊的最後幾行看到。我們可以看到結果輸出中有一個 NaN 值,這是因為兩個 Series 的長度不相等。

示例

result = sr1.add(sr2, fill_value=0)

print('The resultant series object of adding two series with fill_value:', result)

解釋

為了去除前面輸出中的 NaN 值,這裡我們將 '0' 值替換為 fill_value 引數。

輸出

The resultant series object of adding two series with fill_value:
0  16.0
1  14.0
2  19.0
3  16.0
4   5.0
dtype: float64

我們可以看到此輸出中不存在 NaN 值,這是由於 fill_value 引數導致的。在此示例中,我們將 0 作為輸入提供給 fill_value 引數,以便它將缺失值與 0 相加。

示例

import pandas as pd
import numpy as np

sr1 = pd.Series({'a':1,'b':2,'c':3})
print('Series Object 1:',sr1)

sr2 = pd.Series({'c':7,'d':8,'e':9})

print('Series Object 2:',sr2)

result1 = sr1.add(sr2)

print('Resultant series object without Fill_value:', result1)

result2 = sr1.add(sr2, fill_value= 0)

print('Resultant series object with Fill_value 0:', result2)

解釋

在以下示例中,我們使用 Python 字典建立了兩個 Pandas Series 物件,它們具有不同的索引標籤。

我們透過兩種方式對這兩個 Series 物件進行了加法運算,一種是替換 fill_value 引數,另一種是不定義引數輸入。

輸出

Series Object 1:
a   1
b   2
c   3
dtype: int64

Series Object 2:
c   7
d   8
e   9
dtype: int64

Resultant series object without Fill_value:
a   NaN
b   NaN
c  10.0
d   NaN
e   NaN
dtype: float64

Resultant series object with Fill_value 0:
a   1.0
b   2.0
c  10.0
d   8.0
e   9.0
dtype: float64

兩個 Series 之間的加法是基於索引標籤進行的,如果索引不相同,則 add 函式將自動匹配那些缺失的索引並替換為 NaN,然後執行加法運算。這就是我們在 add() 函式的結果輸出中看到 NaN 值的原因。

更新於: 2021年11月18日

550 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.