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


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

Series.str可用於以字符串形式訪問係列的值並對其應用幾種方法。 Pandas Series.str.decode()函數用於使用指示的編碼來解碼係列/索引中的字符串。此函數等效於str.decode()在python2和bytes.decode()在python3中。

用法: Series.str.decode(encoding, errors=’strict’)

參數:
encoding:str
errors:str,可選


返回:解碼的對象序列/索引

範例1:采用Series.str.decode()函數解碼給定係列對象的基礎數據中的字符串。使用“ UTF-8”編碼方法。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series([b"b'New_York'", b"b'Lisbon'", b"b'Tokyo'", b"b'Paris'", b"b'Munich'"]) 
  
# Creating the index 
idx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] 
  
# set the index 
sr.index = idx 
  
# Print the series 
print(sr)

輸出:

現在我們將使用Series.str.decode()函數解碼給定係列對象的基礎數據中的字符串。

# use 'UTF-8' encoding 
result = sr.str.decode(encoding = 'UTF-8') 
  
# print the result 
print(result)

輸出:

正如我們在輸出中看到的,Series.str.decode()函數已成功解碼給定係列對象的基礎數據中的字符串。

範例2:采用Series.str.decode()函數解碼給定係列對象的基礎數據中的字符串。使用“ ASCII”編碼方法。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series([b'Mike-', b'Alessa-', b'Nick-', b'Kim-', b'Britney-']) 
  
# Creating the index 
idx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] 
  
# set the index 
sr.index = idx 
  
# Print the series 
print(sr)

輸出:


現在我們將使用Series.str.decode()函數解碼給定係列對象的基礎數據中的字符串。

# use 'ASCII' encoding 
result = sr.str.decode(encoding = 'ASCII') 
  
# print the result 
print(result)

輸出:

正如我們在輸出中看到的,Series.str.decode()函數已成功解碼給定係列對象的基礎數據中的字符串。



相關用法


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