Python 使用re.sub()从数据帧中删除所有其他内容时出错
我有一个df,作为一些变量,其中包含字母数字文本Python 使用re.sub()从数据帧中删除所有其他内容时出错,python,pandas,Python,Pandas,我有一个df,作为一些变量,其中包含字母数字文本 data = { col1: ['xyz Res ' ' Navigation' 'After Hours' 'Internal review @!'], col2: ['Help?Desk' 'Supplier @ 123 &%' 'Unprofiled Manager ? ' 'Air ? Online'] } 我想要一个没有空格的DF,特殊字符,如@!&%?等等 我正在尝试使用以下代码删除padas dataf
data = {
col1: ['xyz Res ' ' Navigation' 'After Hours' 'Internal review @!'],
col2: ['Help?Desk' 'Supplier @ 123 &%' 'Unprofiled Manager ? ' 'Air ? Online']
}
我想要一个没有空格的DF,特殊字符,如@!&%?等等
我正在尝试使用以下代码删除padas dataframe中除字母数字以外的所有内容:
df = df.apply(lambda x: x.re.sub('[^a-zA-Z\d\s]', '', x) if x.dtype == "object" else x)
这是一个错误:
AttributeError: ("'Series' object has no attribute 're'", 'occurred at index col1')
有什么帮助吗?请使用
str.replace
:
data = {"col1": ['xyz Res ' ' Navigation' 'After Hours' 'Internal review @!',
'Help?Desk' 'Supplier @ 123 &%' 'Unprofiled Manager ? ' 'Air ? Online'],}
df = pd.DataFrame(data)
df["col1"] = df["col1"].str.replace('[^a-zA-Z\d\s]', '')
print (df)
col1
0 xyz Res NavigationAfter HoursInternal re...
1 HelpDeskSupplier 123 Unprofiled Manager A...
改用
str.replace
:
data = {"col1": ['xyz Res ' ' Navigation' 'After Hours' 'Internal review @!',
'Help?Desk' 'Supplier @ 123 &%' 'Unprofiled Manager ? ' 'Air ? Online'],}
df = pd.DataFrame(data)
df["col1"] = df["col1"].str.replace('[^a-zA-Z\d\s]', '')
print (df)
col1
0 xyz Res NavigationAfter HoursInternal re...
1 HelpDeskSupplier 123 Unprofiled Manager A...
你能举一个可复制的例子吗?另外,抛出了什么错误?
x
是一个系列
。对于系列
,没有re.sub
方法。你所需要的是相当于re.sub
。你能举一个可复制的例子吗?另外,抛出了什么错误?x
是一个系列
。对于系列
,没有re.sub
方法。您需要的是相当于re.sub
。谢谢。这真的很有用。谢谢。这真的很有用。