Pandas Series.str.lower() 方法



Python Pandas 庫中的Series.str.lower()方法用於將 Series 或 Index 中的字串轉換為小寫。此方法對於文字規範化和資料預處理非常有用,因為它透過將所有字元轉換為小寫來確保文字資料的一致性。

使用此方法可以更有效地執行不區分大小寫的比較和分析。這等效於 Python 的內建str.lower()方法,通常用於資料清洗和預處理任務。

語法

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

Series.str.lower()

引數

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

返回值

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

示例 1

讓我們來看一個基本的例子,瞭解 Series.str.lower() 方法是如何工作的:

import pandas as pd

# Create a Series
s = pd.Series(['Hello', 'WORLD', 'Pandas'])

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

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

執行上述程式後,會產生以下結果:

Input Series
0    Hello
1    WORLD
2    Pandas
dtype: object

Series after applying the lower:
0    hello
1    world
2    pandas
dtype: object

示例 2

在這個例子中,我們將演示在 DataFrame 中使用 Series.str.lower() 方法。

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'CHARLIE'], 'Role': ['ADMIN', 'User', 'Manager']})

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

# Apply the lower method to the 'Role' column
df['Role'] = df['Role'].str.lower()

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

以上程式碼的輸出如下:

Input DataFrame
    Name     Role
0  Alice    ADMIN
1    Bob     User
2  CHARLIE  Manager

Modified DataFrame
    Name     Role
0  Alice    admin
1    Bob     user
2  CHARLIE  manager

示例 3

讓我們來看另一個例子,我們將 Series.str.lower() 方法應用於 pandas DataFrame 的索引物件。

import pandas as pd

# Create a DataFrame with an Index
df = pd.DataFrame({'Value': [1, 2, 3]}, index=['First', 'SECOND', 'THIRD'])

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

# Apply lower to the DataFrame index labels
df.index = df.index.str.lower()

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

以上程式碼的輸出如下:

Original DataFrame:
        Value
First       1
SECOND      2
THIRD       3
Modified DataFrame:
        Value
first       1
second      2
third       3
python_pandas_working_with_text_data.htm
廣告