剥离/修剪数据帧的所有字符串

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.

注意:值不能typesdicts或者lists,因为它们dtypesobject.

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)

  • 在这种情况下,应忽略SettingWithCopyWarning,如下所述:/sf/ask/1443790771/?answertab=oldest#tab-top (3认同)
  • 如果你有 N/A 之类的字符串,你需要在执行 df_obj.apply 时添加参数 na_action="ignore"),否则 pandas 会将这些值转换为空字符串 (2认同)

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


Rom*_*kar 8

如果你真的想使用正则表达式,那么

>>> 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)


Dek*_*kel 7

您可以使用该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)

请注意使用stripand 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)

  • `df[0] = df[0].str.strip()` - 在更大的 DF 上很可能会更快 (2认同)

小智 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)