如何在 Pandas Series 中應用整數除法運算子?


整數除法運算也稱為向下取整除法,在 Python 中等效於 //。它是一個二元運算,也就是一個按元素進行除法運算的操作,並返回一個新值。

在 Pandas Series 類中,有一個名為 floordiv() 的方法,它執行 Series 物件與標量之間的按元素整數除法運算。此方法也可用於執行兩個 Series 物件之間的向下取整除法。

此方法的輸出是一個包含運算結果的新 Series。它有三個引數:fill_value、other 和 level。other 引數就是第二個輸入(另一個 Series 或標量)。fill_value 引數用於在執行 floordiv() 方法時用指定值替換缺失值,預設情況下,該引數將用 Nan 填充缺失值。

示例 1

在以下示例中,我們將對 Series 物件應用向下取整除法運算,除數為標量值“2”。

import pandas as pd

# create pandas Series
series = pd.Series([9, 25, 14, 82])

print("Series object:",series)

# apply floordiv()
print("Output:")
print(series.floordiv(2))

輸出

輸出如下所示:

Series object:
0    9
1    25
2    14
3    82
dtype: int64

Output:
0    4
1    12
2    7
3    41
dtype: int64

在上面的程式碼塊中,我們可以看到初始 Series 物件和結果 Series 物件。第二個物件是 Series 與標量值“2”之間按元素進行整數除法運算的結果。

示例 2

在以下示例中,我們將對包含一些 Nan 值的 Series 物件應用整數除法運算,除數為標量。

import pandas as pd
import numpy as np

# create pandas Series
series = pd.Series([87, 5, None, 42, np.nan, 61])

print("Series object:",series)

# apply floordiv()
print("Output without replacing missing values:")
print(series.floordiv(other=2))

# apply floordiv() method with fill_value parameter
print("Output with replacing missing values by 5:")
print(series.floordiv(other=2, fill_value=5))

輸出

輸出如下所示:

Series object:
0    87.0
1    5.0
2    NaN
3    42.0
4    NaN
5    61.0
dtype: float64

Output without replacing missing values:
0    43.0
1    2.0
2    NaN
3    21.0
4    NaN
5    30.0
dtype: float64

Output with replacing missing values by 5:
0    43.0
1    2.0
2    2.0
3    21.0
4    2.0
5    30.0
dtype: float64

首先,我們在不替換缺失值的情況下,對 Series 物件應用了向下取整除法運算,除數為標量值 2。然後,我們再次對同一個 Series 應用了 floordiv() 方法,除數為標量值 2,並且將缺失值填充為 5 (fill_value=5)。

這兩個輸出都在上面的輸出程式碼塊中顯示。

更新於: 2022年3月7日

606 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.