當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas Series.apply()用法及代碼示例

Pandas 係列是帶有軸標簽的一維ndarray。標簽不必是唯一的,但必須是可哈希的類型。該對象同時支持基於整數和基於標簽的索引,並提供了許多方法來執行涉及索引的操作。

Pandas Series.apply()函數在給定係列對象的每個元素上調用傳遞的函數。

用法: Series.apply(func, convert_dtype=True, args=(), **kwds)

參數:
func:適用Python函數或NumPy ufunc。
convert_dtype:嘗試找到更好的dtype以獲得逐元素函數結果。
args:在係列值之後將位置參數傳遞給func。
** kwds:傳遞給func的其他關鍵字參數。

返回:係列

範例1:采用Series.apply()如果城市是“裏約”,則可以將城市名稱更改為“蒙特利爾”。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) 
  
# Create the Index 
index_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']  
  
# set the index 
sr.index = index_ 
  
# Print the series 
print(sr)

輸出:

City 1    New York
City 2     Chicago
City 3     Toronto
City 4      Lisbon
City 5         Rio
dtype:object

現在我們將使用Series.apply()如果城市是“裏約”,則可以將城市名稱更改為“蒙特利爾”。

# change 'Rio' to 'Montreal' 
# we have used a lambda function 
result = sr.apply(lambda x:'Montreal' if x =='Rio' else x ) 
  
# Print the result 
print(result)

輸出:

City 1    New York
City 2     Chicago
City 3     Toronto
City 4      Lisbon
City 5    Montreal
dtype:object

正如我們在輸出中看到的,Series.apply()函數已成功將城市名稱更改為“蒙特利爾”。

範例2:采用Series.apply()如果給定係列對象中的值大於30,則函數返回True,否則返回False。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) 
  
# Create the Index 
# apply yearly frequency 
index_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') 
  
# set the index 
sr.index = index_ 
  
# Print the series 
print(sr)

輸出:

2010-12-31 08:45:00    11.0
2011-12-31 08:45:00    21.0
2012-12-31 08:45:00     8.0
2013-12-31 08:45:00    18.0
2014-12-31 08:45:00    65.0
2015-12-31 08:45:00    18.0
2016-12-31 08:45:00    32.0
2017-12-31 08:45:00    10.0
2018-12-31 08:45:00     5.0
2019-12-31 08:45:00    32.0
2020-12-31 08:45:00     NaN
Freq:A-DEC, dtype:float64

現在我們將使用Series.apply()如果給定係列對象中的值大於30,則函數返回True,否則返回False。

# return True if greater than 30 
# else return False 
result = sr.apply(lambda x:True if x>30 else False) 
  
# Print the result 
print(result)

輸出:

2010-12-31 08:45:00    False
2011-12-31 08:45:00    False
2012-12-31 08:45:00    False
2013-12-31 08:45:00    False
2014-12-31 08:45:00     True
2015-12-31 08:45:00    False
2016-12-31 08:45:00     True
2017-12-31 08:45:00    False
2018-12-31 08:45:00    False
2019-12-31 08:45:00     True
2020-12-31 08:45:00    False
Freq:A-DEC, dtype:bool

正如我們在輸出中看到的,Series.apply()函數已成功返回給定series對象的numpy數組表示形式。



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas Series.apply()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。