Pandas Series.str.encode() 方法



Pandas 中的Series.str.encode() 方法用於使用指定的編碼將 Series 或 Index 中的字元字串編碼為位元組字串。此方法對於將文字資料轉換為編碼格式以進行儲存或傳輸很有用。

此方法類似於str.encode() 方法,它提供了一種簡單的方法來處理 Pandas Series 或 Index 中文字資料的編碼。

語法

以下是 Pandas Series.str.encode() 方法的語法:

Series.str.encode(encoding, errors='strict')

引數

Series.str.encode() 方法接受以下引數:

  • encoding - 表示用於對文字進行編碼的編碼名稱的字串。

  • errors - 一個可選字串,指定如何處理編碼錯誤。預設值為 'strict',在編碼錯誤時引發 UnicodeEncodeError。其他選項包括 'ignore'、'replace'、'backslashreplace' 和 'namereplace'。

返回值

Series.str.encode() 方法返回一個與呼叫物件型別相同的 Series 或 Index,其中包含編碼後的位元組字串。

示例

在此示例中,我們透過使用 'ascii' 編碼對字串的 Series 進行編碼來演示 Series.str.encode() 方法的基本用法。

import pandas as pd

# Create a Series of strings
ser = pd.Series(['Tutorialspoint', '123', '$'])

# Encode strings using 'ascii' encoding
result = ser.str.encode('ascii')

print("Input Series:")
print(ser)
print("\nSeries after calling str.encode('ascii'):")
print(result)

當我們執行以上程式碼時,它會產生以下輸出:

Input Series:
0    Tutorialspoint
1               123
2                 $
dtype: object

Series after calling str.encode('ascii'):
0    b'Tutorialspoint'
1               b'123'
2                 b'$'
dtype: object

示例

此示例演示瞭如何使用 Series.str.encode() 方法使用 'utf-8' 編碼對 DataFrame 中字串列進行編碼。

import pandas as pd

# Create a DataFrame with a column of strings
df = pd.DataFrame({ 'COLUMN1': ['©', '€', '🇀'] })

# Encode strings using 'utf-8' encoding
result = df['COLUMN1'].str.encode('utf-8')

print("Input DataFrame:")
print(df)
print("\nDataFrame column after calling str.encode('utf-8'):")
print(result)

以下是上述程式碼的輸出:

Input DataFrame:
  COLUMN1
0       ©
1       €
2     🇀

DataFrame column after calling str.encode('utf-8'):
0    b'\xc2\xa9'
1    b'\xe2\x82\xac'
2    b'\xf0\x9f\x87\x80'
Name: COLUMN1, dtype: object

示例

這是另一個示例,演示瞭如何使用 Series.str.encode() 方法使用 'utf-8' 編碼對包含特殊字元的字串進行編碼。

import pandas as pd

# Create a Series of strings with special characters
ser = pd.Series(['✔', '✓', '✜'])

# Encode strings using 'utf-8' encoding
result = ser.str.encode('utf-8')

print("Input Series:")
print(ser)
print("\nSeries after calling str.encode('utf-8'):")
print(result)

以下是上述程式碼的輸出:

Input Series:
0    ✔
1    ✓
2    ✜
dtype: object

Series after calling str.encode('utf-8'):
0    b'\xe2\x9c\x94'
1    b'\xe2\x9c\x93'
2    b'\xe2\x9c\x9c'
dtype: object
python_pandas_working_with_text_data.htm
廣告