Pandas Series.str.casefold() 方法



Pandas 中的 Series.str.casefold() 方法用於將 Series 或 Index 中的字串轉換為小寫形式。Casefolding 是一種更激進的小寫轉換形式,用於文字規範化。它尤其適用於執行不區分大小寫的比較以及以更統一的方式處理文字。

此方法等效於 Python 的內建 str.casefold() 方法,通常用於資料分析任務中標準化文字資料。

語法

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

Series.str.casefold()

引數

Pandas Series.str.casefold() 方法不接受任何引數。

返回值

Series.str.casefold() 方法返回一個形狀相同的 Series 或 Index,其中每個字串都已轉換為小寫形式。這意味著每個字串中的所有字元都轉換為其小寫形式。

示例 1

讓我們來看一個基本的示例,以瞭解 Series.str.casefold() 方法的工作原理:

import pandas as pd

# Create a Series
s = pd.Series(['Hi', 'WELCOME to', 'TUTORIALSPOINT'])

# Display the input Series
print("Input Series")
print(s)

# Apply the casefold method
print("Series after applying the casefold:")
print(s.str.casefold())

執行以上程式時,它會產生以下結果:

Input Series
0                Hi
1        WELCOME to
2    TUTORIALSPOINT
dtype: object

Series after applying the casefold:
0                hi
1        welcome to
2    tutorialspoint
dtype: object

示例 2

在此示例中,我們將演示在 DataFrame 中使用 Series.str.casefold() 方法:

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], 'Subject': ['Math', 'English', 'Science', 'Music', 'Games']})

# Print the original DataFrame
print("Input DataFrame")
print(df)

# Apply the casefold method to the 'Day' column
df.Day = df.Day.str.casefold()

# Print the modified DataFrame
print("Modified DataFrame:")
print(df)

以上程式碼的輸出如下:

Original DataFrame:
   Day  Subject
0  Mon     Math
1  Tue  English
2  Wed  Science
3  Thu    Music
4  Fri    Games

Modified DataFrame:
   Day  Subject
0  mon     Math
1  tue  English
2  wed  Science
3  thu    Music
4  fri    Games

示例 3

讓我們再看一個示例,其中我們在更復雜的場景中應用 Series.str.casefold()

import pandas as pd

# Create a DataFrame with mixed-case text
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'CHARLIE', 'david'], 'Role': ['Admin', 'user', 'MANAGER', 'staff']})

# Print the original DataFrame
print("Original DataFrame:")
print(df)

# Apply casefold to both 'Name' and 'Role' columns
df = df.apply(lambda x: x.str.casefold() if x.dtype == "object" else x)

# Print the modified DataFrame
print("Modified DataFrame:")
print(df)

以上程式碼的輸出如下:

Original DataFrame:
      Name     Role
0    Alice    Admin
1      Bob     user
2  CHARLIE  MANAGER
3    david    staff

Modified DataFrame:
      Name     Role
0    alice    admin
1      bob     user
2  charlie  manager
3    david    staff
python_pandas_working_with_text_data.htm
廣告