bol*_*old 51 python regex trim dataframe pandas
在python/pandas中清理multitype数据框的值,我想修剪字符串.我目前正在两个指令中执行此操作:
import pandas as pd
df = pd.DataFrame([[' a ', 10], [' c ', 5]])
df.replace('^\s+', '', regex=True, inplace=True) #front
df.replace('\s+$', '', regex=True, inplace=True) #end
df.values
Run Code Online (Sandbox Code Playgroud)
这很慢,我能改进什么?
jez*_*ael 109
您可以使用DataFrame.select_dtypes
选择string
列然后apply
运行str.strip
.
注意:值不能types
像dicts
或者lists
,因为它们dtypes
是object
.
df_obj = df.select_dtypes(['object'])
print (df_obj)
0 a
1 c
df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
print (df)
0 1
0 a 10
1 c 5
Run Code Online (Sandbox Code Playgroud)
但如果只有几列使用str.strip
:
df[0] = df[0].str.strip()
Run Code Online (Sandbox Code Playgroud)
Jon*_* B. 43
这是一个使用简洁版本的applymap
简单lambda表达式,strip
只有当值是字符串类型时才调用:
df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
Run Code Online (Sandbox Code Playgroud)
一个更完整的例子:
import pandas as pd
def trim_all_columns(df):
"""
Trim whitespace from ends of each value across all series in dataframe
"""
trim_strings = lambda x: x.strip() if isinstance(x, str) else x
return df.applymap(trim_strings)
# simple example of trimming whitespace from data elements
df = pd.DataFrame([[' a ', 10], [' c ', 5]])
df = trim_all_columns(df)
print(df)
>>>
0 1
0 a 10
1 c 5
Run Code Online (Sandbox Code Playgroud)
这是一个由饰品托管的工作示例:https: //trinket.io/python3/65078f3cdf
如果你真的想使用正则表达式,那么
>>> df.replace('(^\s+|\s+$)', '', regex=True, inplace=True)
>>> df
0 1
0 a 10
1 c 5
Run Code Online (Sandbox Code Playgroud)
但这样做应该更快:
>>> df[0] = df[0].str.strip()
Run Code Online (Sandbox Code Playgroud)
您可以使用该apply
功能的的Series
对象:
>>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
>>> df[0][0]
' a '
>>> df[0] = df[0].apply(lambda x: x.strip())
>>> df[0][0]
'a'
Run Code Online (Sandbox Code Playgroud)
请注意使用
strip
and not theregex
哪个更快
另一种选择 - 使用DataFrame 对象的apply
功能:
>>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
>>> df.apply(lambda x: x.apply(lambda y: y.strip() if type(y) == type('') else y), axis=0)
0 1
0 a 10
1 c 5
Run Code Online (Sandbox Code Playgroud)
小智 7
你可以试试:
df[0] = df[0].str.strip()
Run Code Online (Sandbox Code Playgroud)
或者更具体地说是所有字符串列
non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())
Run Code Online (Sandbox Code Playgroud)