Python:在以日期时间为列的数据帧上应用正则表达式

时间:2019-02-28 05:55:01

标签: regex pandas datetime

我有一个数据框(df)如下

Index     Month     Time       Text_1          Text_2                 Text_3
  0      02/2019   19:44:33   aadd@34:9984    (none)\       62fa6297-f5f5-4c47-8236-4a85cad5e601
                                             STBROWN2-M-26YQ
  1      02/2019   19:30:22   58:EF:68:14    (none)\        f933fb2a-4dde-a547-80ca-3b9e6cd29a6d
                                             STBROWN2-M-26YQ

我编写了一个简单的正则表达式,如下所示

def clean(text):
text = text.lower()
text_clean = re.sub('[^A-Za-z0-9]', ' ', text)
return text_clean

然后我将以上内容应用于df

df.apply(lambda x : clean(x))

我遇到以下错误:

AttributeError: ("'Series' object has no attribute 'lower'", 'occurred at index Application')

可能是因为MonthTime列是datetime对象。

我的问题是:如何在忽略日期时间的同时应用正则表达式?

2 个答案:

答案 0 :(得分:2)

使用过滤器选择以文本开头的列

def clean(text):
    text = text.str.lower()
    text_clean = text.str.replace('[^A-Za-z0-9]', ' ', regex = True)
    return text_clean
df.assign(**df.filter(like = 'Text').apply(clean))

答案 1 :(得分:1)

在您的数据中,我认为所有数据都是字符串,但是如果要排除datetimes列,请使用select_dtypes

def clean(text):
    return text.str.lower().str.replace('[^A-Za-z0-9]', '')

#filter only object columns
mask = df.dtypes == 'object'
#filter Text columns if possible
#mask = df.columns.startswith('Text')

df.loc[:, mask] = df.loc[:, mask].apply(clean)