13_Pandas字符串的替换和空白处删除等方法
在pandas中,准备了处理字符串的方法,以便共同处理pandas.DataFrame的列和行(= pandas.Series)的字符串。
以下的方法与标准Python字符串(str类型对象)的方法相同。
- 替换
- str.replace():替换字符串
- 空白削除
- str.strip():删除左右两侧的空白(开始/结束)
- str.lstrip():删除左侧空白
- str.rstrip():删除右侧空白
- 大小写変换
- str.lower():转换为小写
- str.upper():转换为大写
- str.capitalize():将第一个字母转换为大写,将其他字母转换为小写
- str.title():将单词的首字母转换为大写,其余转换为小写
将描述每个示例。
有关使用字符串方法的其他方法,请参见以下文章。
替换
str.replace():替换字符串
import pandas as pd
s = pd.Series([' a-a-x ', ' b-x-b ', ' x-c-c '])
print(s)
# 0 a-a-x
# 1 b-x-b
# 2 x-c-c
# dtype: object
s_new = s.str.replace('x', 'z')
print(s_new)
# 0 a-a-z
# 1 b-z-b
# 2 z-c-c
# dtype: object
要更新(替换)pandas.DataFrame的列,请将其替换为原始列。与其他方法相同。
df = pd.DataFrame([[' a-a-x-1 ', ' a-a-x-2 '],
[' b-x-b-1 ', ' b-x-b-2 '],
[' x-c-c-1 ', ' x-c-c-2 ']],
columns=['col1', 'col2'])
print(df)
# col1 col2
# 0 a-a-x-1 a-a-x-2
# 1 b-x-b-1 b-x-b-2
# 2 x-c-c-1 x-c-c-2
df['col1'] = df['col1'].str.replace('x', 'z')
print(df)
# col1 col2
# 0 a-a-z-1 a-a-x-2
# 1 b-z-b-1 b-x-b-2
# 2 z-c-c-1 x-c-c-2
空白削除
str.strip():删除左右两侧的空白(开始/结束)
s_new = s.str.strip()
print(s_new)
# 0 a-a-x
# 1 b-x-b
# 2 x-c-c
# dtype: object
也可以指定要删除的字符作为参数。指定字符串中包含的字符将被删除。这同样适用于str.lstrip()和str.rstrip()。
s_new = s.str.strip(' x')
print(s_new)
# 0 a-a-
# 1 b-x-b
# 2 -c-c
# dtype: object
对于pandas.DataFrame。与str.replace()相同。
df['col1'] = df['col1'].str.strip()
print(df)
# col1 col2
# 0 a-a-z-1 a-a-x-2
# 1 b-z-b-1 b-x-b-2
# 2 z-c-c-1 x-c-c-2
str.lstrip():删除左侧空白
s_new = s.str.lstrip()
print(s_new)
# 0 a-a-x
# 1 b-x-b
# 2 x-c-c
# dtype: object
str.rstrip():删除右侧空白
s_new = s.str.rstrip()
print(s_new)
# 0 a-a-x
# 1 b-x-b
# 2 x-c-c
# dtype: object
大小写変换
以下pandas.Series为例。
s = pd.Series(['Hello World', 'hello world', 'HELLO WORLD'])
print(s)
# 0 Hello World
# 1 hello world
# 2 HELLO WORLD
# dtype: object
pandas.DataFrame同样适用该方法。
str.lower():转换为小写
s_new = s.str.lower()
print(s_new)
# 0 hello world
# 1 hello world
# 2 hello world
# dtype: object
str.upper():转换为大写
s_new = s.str.upper()
print(s_new)
# 0 HELLO WORLD
# 1 HELLO WORLD
# 2 HELLO WORLD
# dtype: object
str.capitalize():将第一个字母转换为大写,将其他字母转换为小写
s_new = s.str.capitalize()
print(s_new)
# 0 Hello world
# 1 Hello world
# 2 Hello world
# dtype: object
str.title():将单词的首字母转换为大写,其余转换为小写
s_new = s.str.title()
print(s_new)
# 0 Hello World
# 1 Hello World
# 2 Hello World
# dtype: object