繁体   English   中英

在 Dataframe 的整个列中应用正则表达式

[英]Applying Regex across entire column of a Dataframe

我有一个包含 3 列的数据框:

id,name,team 
101,kevin, marketing
102,scott,admin\n
103,peter,finance\n

我正在尝试应用正则表达式函数,以便删除不必要的空格。 我有删除这些空格的代码,但我无法在整个 Dataframe 中循环它。

到目前为止,这是我尝试过的:

df['team'] = re.sub(r'[\n\r]*','',df['team'])

但这会引发错误AttributeError: 'Series' object has no attribute 're'

谁能建议我如何通过整个 Dataframe df['team']列循环这个正则表达式

你快到了,有两种简单的方法可以做到这一点:

# option 1 - faster way
df['team'] =  [re.sub(r'[\n\r]*','', str(x)) for x in df['team']]

# option 2
df['team'] =  df['team'].apply(lambda x: re.sub(r'[\n\r]*','', str(x)))

只要它是数据框检查替换https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html

df['team'].replace( { r"[\n\r]+" : '' }, inplace= True, regex = True)

关于正则表达式,'*' 表示 0 或更多,你应该需要 '+' 是 1 或更多

这是一种无需循环即可一步替换 pandas 列中多个单词的强大技术。 在我的代码中,我想在不使用循环的情况下从我的列中删除诸如“CORPORATION”、“LLC”等内容(所有这些都在 RemoveDB.csv 文件中)。 在这种情况下,我将一步从整列中删除 40 个单词。

RemoveDB = pd.read_csv('RemoveDBcsv')
RemoveDB = RemoveDB['REMOVE'].tolist()
RemoveDB = '|'.join(RemoveDB)
pattern = re.compile(RemoveDB)    
df['NAME']= df['NAME'].str.replace(pattern,'', regex = True)

另一个例子(但没有正则表达式)但可能对某人仍然有用。

id = pd.Series(['101','102','103'])
name = pd.Series(['kevin','scott','peter'])
team = pd.Series(['     marketing','admin\n', 'finance\n'])

testsO = pd.DataFrame({'id': id, 'name': name, 'team': team})
print(testsO)
testsO['team'] = testsO['team'].str.strip()
print(testsO)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM