如何使用另一個序列物件對 Pandas 序列物件應用地板除法?


Pandas 序列構造器中的 floordiv() 方法用於執行兩個序列物件的整數除法(逐元素除法運算),地板除法運算也稱為整數除法,它等效於 Python 中的 //。該方法支援替換任何輸入中的缺失值。

該方法返回一個包含結果值的序列,並且該方法具有 3 個引數:fill_value、other 和 level。other 引數只是第二個輸入物件,可以是序列或標量。

fill_value 引數用於在執行 floordiv() 方法時替換缺失值位置的特定值;預設情況下,它將用 Nan 填充缺失值。

示例 1

在這個例子中,我們將使用 floordiv() 方法在兩個序列物件之間應用整數除法運算,而無需更改任何預設引數值。

# import pandas packages
import pandas as pd

# Creating Pandas Series objects
series1 = pd.Series([57, 47, 81, 88, 43], index=['A', 'B', 'C', 'D', 'E'])
print('First series object:',series1)

series2 = pd.Series([1, 5, 4, 7, 9], index=['A', 'B', 'C', 'D', 'F'])
print('Second series object:',series2)

# apply floor division
print("Floordiv of Series1 and Series2:", series1.floordiv(series2))

輸出

輸出如下:

First series object:
A    57
B    47
C    81
D    88
E    43
dtype: int64

Second series object:
A    1
B    5
C    4
D    7
F    9
dtype: int64

Floordiv of Series1 and Series2:
A    57.0
B    9.0
C    20.0
D    12.0
E    NaN
F    NaN
dtype: float64

在上面的輸出塊中,我們可以看到兩個輸入序列物件以及結果序列物件。在結果序列中,存在兩個 Nan 元素,因為第二個序列物件中沒有索引位置“E”的值,而被呼叫序列物件中也沒有標籤“F”。

示例 2

與前面的示例一樣,我們建立了兩個帶有標記索引的 Pandas 序列。之後,我們使用 fill_value 引數應用 floordiv() 方法。

# import pandas packages
import pandas as pd

# Creating Series objects
series1 = pd.Series([10, 14, 82, 49, 82], index=['A', 'B', 'C', 'D', 'E'])
print('First series object:')
print(series1)

series2 = pd.Series([2, 6, 4, 4, 5], index=['A', 'B', 'C', 'D', 'F'])
print('Second series object:')
print(series2)

# Apply the floordiv method
print("Floordiv of Series1 and Series2:")
print(series1.floordiv(series2, fill_value=10))

輸出

輸出如下:

First series object:
A    10
B    14
C    82
D    49
E    82
dtype: int64

Second series object:
A    2
B    6
C    4
D    4
F    5
dtype: int64

Floordiv of Series1 and Series2:
A    5.0
B    2.0
C    20.0
D    12.0
E    8.0
F    2.0
dtype: float64

我們可以觀察到輸出序列物件中的 Nan 值被替換為 10。

更新於:2022年3月7日

瀏覽量:113

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.