如何在 Pandas Series 上應用匿名函式?
Pandas Series 建構函式具有一個 apply() 方法,它接受任何應用於給定 Series 物件值的自定義函式。
同樣,我們可以在 Pandas Series 物件上應用匿名函式。我們可以在 Pandas 的兩個資料結構 DataFrame 和 Series 上使用此 apply() 方法。它執行逐元素轉換並返回一個新的 Series 物件作為結果。
示例 1
# import pandas package
import pandas as pd
import numpy as np
# create a pandas series
s = pd.Series(np.random.randint(10,20,5))
print(s)
# Applying an anonymous function
result = s.apply(lambda x: x**2)
print('Output of apply method',result)解釋
在以下示例中,我們使用 lambda 函式作為匿名函式傳遞給 apply() 方法。
最初,我們使用 NumPy 隨機模組建立了一個包含 5 個整數值的 Pandas.Series 物件“s”,然後我們使用 apply() 方法和 lambda 函式應用平方函式。
輸出
0 12 1 17 2 11 3 15 4 15 dtype: int32 Output of apply method 0 144 1 289 2 121 3 225 4 225 dtype: int64
程式碼 s.apply(lambda x:x**2) 將計算 Series 元素每個值的平方。這裡 lambda 是一個匿名函式。apply() 方法將返回一個新的 Series 物件,如上述輸出塊中所示。
示例 2
# import pandas package
import pandas as pd
import numpy as np
# create a pandas series
s = pd.Series(np.random.randint(10,20,5))
print(s)
# Applying an anonymous function
result = s.apply(lambda x : True if x%2==0 else False)
print('Output of apply method',result)解釋
讓我們再取一個 Pandas Series 物件並應用一個匿名函式,這裡我們應用了一個 lambda 函式來識別 Series 物件“s”的偶數和奇數值。
輸出
0 15 1 18 2 15 3 14 4 18 dtype: int32 Output of apply method 0 False 1 True 2 False 3 True 4 True dtype: bool
給定示例的 apply() 方法的輸出與實際的 Series 物件“s”一起顯示在上面的程式碼塊中。
結果 Series 物件包含布林值(True 和 False),True 代表偶數,False 代表奇數。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP