Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用re.sub()从数据帧中删除所有其他内容时出错_Python_Pandas - Fatal编程技术网

Python 使用re.sub()从数据帧中删除所有其他内容时出错

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

我有一个df,作为一些变量,其中包含字母数字文本

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
。谢谢。这真的很有用。谢谢。这真的很有用。