Pandas 系列中的 apply() 方法有什麼作用?


Pandas Series 中的 apply() 方法用於在 Series 物件上呼叫我們的函式。透過使用此 apply() 方法,我們可以在 Series 物件上應用我們自己的函式。

apply() 方法與其他一些 Pandas Series 方法(如 agg() 和 map())非常相似。這裡的區別在於我們可以對給定 Series 物件的值應用函式。

示例 1

# import pandas package
import pandas as pd

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# Applying a function
result = s.apply(type)
print('Output of apply method',result)

解釋

在下面的示例中,我們建立了一個 pandas.Series 物件“s”,其中包含 10 個整數值,並透過使用 apply() 方法執行 Series 物件“s”所有元素的 type 函式。

apply() 方法的操作類似於 agg() 方法,但區別在於 agg() 方法僅用於聚合操作,而 apply() 方法可用於對 Series 資料應用任何方法。

輸出

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9 10
dtype: int64

Output of apply method
0  <class 'int'>
1  <class 'int'>
2  <class 'int'>
3  <class 'int'>
4  <class 'int'>
5  <class 'int'>
6  <class 'int'>
7  <class 'int'>
8  <class 'int'>
9  <class 'int'>
dtype: object

Pandas Series apply() 方法將返回一個新的 Series 物件,其中包含給定 Series 物件“s”的每個值的 data type 表示。

示例 2

# import pandas package
import pandas as pd

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# Apply power(2) function
result = s.apply(pow, args=(2,))
print('Output of apply method',result)

解釋

讓我們再舉一個例子,並透過使用 apply() 方法將帶有引數的函式應用於 Series 物件。在這裡,我們應用了帶有引數值 2 的 pow 函式。

輸出

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9 10
dtype: int64
Output of apply method
0   1
1   4
2   9
3  16
4  25
5  36
6  49
7  64
8  81
9 100
dtype: int64

apply() 方法的輸出與實際的 Series 物件“s”一起顯示在上面的程式碼塊中。pow() 函式應用於 Series 元素,結果輸出作為另一個 Series 物件返回。

要在 apply() 方法中傳送函式的引數,我們需要使用 args 關鍵字引數。

更新於: 2022-03-09

173 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.