在数据框Pandas中的正则表达式之后替换数据框中的单元格

时间:2019-06-16 14:00:19

标签: python regex pandas dataframe replace

我有这个数据框,我想用空值替换任何包含字母字符的单元格。

df = pd.DataFrame(dict(A = pd.Series(['AB5 La2','-1','8577Y--00']), B = pd.Series(['2\nDate','-45.00','-'])))

df.replace(['.*[a-zA-Z].*'], [''], regex=True , inplace=True)

df

最初,数据框为: enter image description here

我得到了这个数据框: enter image description here

似乎不能替换所有单元格

我想要的是在包含字母字符的情况下用空值替换所有单元格

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

\s
Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v].

https://docs.python.org/3/howto/regex.html

In [44]: df = pd.DataFrame(dict(A = pd.Series(['AB5 La2','-1','8577Y--00']), B = pd.Series(['2\nDate','-45.00','-']))) 
    ...:  
    ...: df.replace(['.*(\s)?[a-zA-Z].*'], [''], regex=True , inplace=True)                                                                                                                  

In [45]: df                                                                                                                                                                                   
Out[45]: 
    A       B
0            
1  -1  -45.00
2           -