我有一列整数(示例行:123456789
),其中一些值散布着垃圾字母。例如:1234y5678
。我想删除出现在此类单元格中的字母并保留数字。我该如何使用熊猫呢?
假设我的数据帧是df
,列名是mobile
。
我应该在np.where
之类的条件下使用df[df['mobile'].str.contains('a-z')]
并使用字符串替换吗?
答案 0 :(得分:4)
如果您的垃圾字符不限于字母,则应使用以下字符:
yourSeries.str.replace('[^0-9]', '')
答案 1 :(得分:2)
使用pd.Series.str.replace
:
import pandas as pd
s = pd.Series(['125109a181', '1361q1j1', '85198m4'])
s.str.replace('[a-zA-Z]', '').astype(int)
输出:
0 125109181
1 136111
2 851984
答案 2 :(得分:1)
使用正则表达式字符类\D
(不是数字):
df['mobile'] = df['mobile'].str.replace('\D', '').astype('int64')