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
广告
© . All rights reserved.