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


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

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

Pandas Series.combine()函數根據函數將係列與係列或標量組合。它將Series和其他使用func的元素組合在一起,以對組合後的Series執行逐元素選擇。當組合的兩個對象之一的某個索引處的值丟失時,假定為fill_value。

用法:  Series.combine(other, func, fill_value=None)

參數:
other:係列或標量
func:以兩個標量為輸入並返回一個元素的函數。
fill_value:一個序列或另一個序列中缺少索引時要采用的值。

返回:係列

範例1:采用Series.combine()函數查找兩個係列對象中每個索引標簽的最大值。

# importing pandas as pd 
import pandas as pd 
  
# Creating the first Series 
sr1 = pd.Series([80, 25, 3, 25, 24, 6]) 
  
# Creating the second Series 
sr2 = pd.Series([34, 5, 13, 32, 4, 15]) 
  
# Create the Index 
index_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] 
  
# set the first index 
sr1.index = index_ 
  
# set the second index 
sr2.index = index_ 
  
# Print the first series 
print(sr1) 
  
# Print the second series 
print(sr2)

輸出:


現在我們將使用Series.combine()函數查找兩個給定係列對象中每個索引標簽的最大值。

# find the maximum element-wise 
# among sr1 and sr2 
result = sr1.combine(other = sr2, func = max) 
  
# Print the result 
print(result)

輸出:

正如我們在輸出中看到的,Series.combine()函數已成功返回兩個係列對象中每個索引標簽的最大值。

範例2:采用Series.combine()函數查找兩個係列對象中每個索引標簽的最小值。

# importing pandas as pd 
import pandas as pd 
  
# Creating the first Series 
sr1 = pd.Series([51, 10, 24, 18, None, 84, 12, 10, 5, 24, 2]) 
  
# Creating the second Series 
sr2 = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) 
  
# Create the Index 
index_ = pd.date_range('2010-10-09', periods = 11, freq ='M') 
  
# set the first index 
sr1.index = index_ 
  
# set the second index 
sr2.index = index_ 
  
# Print the first series 
print(sr1) 
  
# Print the second series 
print(sr2)

輸出:


現在我們將使用Series.combine()函數查找兩個給定係列對象中每個索引標簽的最小值。

# find the minimum element-wise 
# among sr1 and sr2 
result = sr1.combine(other = sr2, func = min) 
  
# Print the result 
print(result)

輸出:

正如我們在輸出中看到的,Series.combine()函數已成功返回兩個係列對象中每個索引標簽的最小值。



相關用法


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