Pandas 中的 str.strip()
方法用于删除 Series 中字符串的开头和结尾的空格。
示例
import pandas as pd
# create a Series
data = pd.Series([' hello ', ' world ', ' pandas '])
# remove trailing and leading whitespaces using str.strip()
trimmed_data = data.str.strip()
print(trimmed_data)
'''
Output
0 hello
1 world
2 pandas
dtype: object
'''
str.strip() 语法
Pandas 中 str.strip()
方法的语法是:
Series.str.strip(to_strip=None)
str.strip() 参数
str.strip()
方法接受以下参数:
to_strip
(可选) - 指定要删除的字符集的字符串。
str.strip() 返回值
str.strip()
方法返回一个 Series,其中从两端移除了指定字符的字符串。
示例 1:使用 str.strip() 删除空格
import pandas as pd
# create a Series with leading and trailing whitespaces
data = pd.Series([' apple ', ' banana ', ' cherry '])
# remove trailing and leading whitespaces using str.strip()
trimmed_data = data.str.strip()
print(trimmed_data)
输出
0 apple 1 banana 2 cherry dtype: object
在这里,我们在 data Series 中使用 data.str.strip()
来删除 data Series 中字符串的开头和结尾的空格。
示例 2:删除特定字符
import pandas as pd
# create a Series with strings surrounded by asterisks
data = pd.Series(['*hello*', '**world**', '***pandas***'])
# use str.strip to remove asterisks (*)
# from the beginning and end of each string
trimmed_data = data.str.strip(to_strip='*')
print(trimmed_data)
输出
0 hello 1 world 2 pandas dtype: object
在上面的示例中,我们使用了 str.strip(to_strip='*')
方法来删除 data Series 中每个字符串开头和结尾的星号 *
。
这里,to_strip
参数设置为 *
,它指定了要删除的字符。