[英]Remove alpha and special characters from the column using python
I am trying to remove alpha characters and special characters(,) from the column values.我正在尝试从列值中删除字母字符和特殊字符(,)。 When trying to remove the alpha characters it gives NaN as output.
当试图删除字母字符时,它给出的 NaN 为 output。
Input Data:输入数据:
col2
2565.0
23899
876.44
1765.7
3,253.0CA
9876.9B
Output Data: Output 数据:
col2
2565.0
23899
876.44
1765.7
3253.0
9876.9
Code i have been using:我一直在使用的代码:
df['col2'] = df['col2'].str.replace(r"[a-zA-Z]",'')
df['col2']=df['col2'].fillna('').str.replace(',',"").astype(float)
Please suggest how to resolve this.请建议如何解决这个问题。
Use Series.replace
and regex which matches "not numbers and dot"使用
Series.replace
和匹配“不是数字和点”的正则表达式
df['col2'] = df.col2.replace('[^\d.]', '', regex=True).astype(float)
Output Output
col2
0 2565.00
1 23899.00
2 876.44
3 1765.70
4 3253.00
5 9876.90
Use Series.str.replace
:使用
Series.str.replace
:
df['col2'] = df['col2'].str.replace(r'[a-zA-Z,]','', regex=True).astype(float)
print (df)
col2
0 2565.00
1 23899.00
2 876.44
3 1765.70
4 3253.00
5 9876.90
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.