我有一个带ID号的大型数据框:
ID.head()
Out[64]:
0 4806105017087
1 4806105017087
2 4806105017087
3 4901295030089
4 4901295030089
Run Code Online (Sandbox Code Playgroud)
这些都是目前的所有字符串.
我想转换为int不使用循环 - 为此我使用ID.astype(int).
问题是我的一些行包含无法转换为的脏数据int,例如
ID[154382]
Out[58]: 'CN414149'
Run Code Online (Sandbox Code Playgroud)
我怎样才能(不使用循环)删除这些类型的事件,以便我可以astype安心使用?
jez*_*ael 56
你需要添加参数errors='coerce'来起作用to_numeric:
ID = pd.to_numeric(ID, errors='coerce')
Run Code Online (Sandbox Code Playgroud)
如果ID是列:
df.ID = pd.to_numeric(df.ID, errors='coerce')
Run Code Online (Sandbox Code Playgroud)
但非数字转换为NaN,所以所有值都是float.
对于int需要转换NaN到一些值,例如,0然后转换为int:
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
Run Code Online (Sandbox Code Playgroud)
样品:
df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
ID
0 4806105017087
1 4806105017087
2 CN414149
print (pd.to_numeric(df.ID, errors='coerce'))
0 4.806105e+12
1 4.806105e+12
2 NaN
Name: ID, dtype: float64
df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
ID
0 4806105017087
1 4806105017087
2 0
Run Code Online (Sandbox Code Playgroud)
OverflowError: Python int too large to convert to C long
Run Code Online (Sandbox Code Playgroud)
用于.astype('int64')64 位有符号整数:
df['ID'] = df['ID'].astype('int64')
Run Code Online (Sandbox Code Playgroud)
如果您不想丢失其中包含字母的值,请使用str.replace()正则表达式模式来删除非数字字符。
df['ID'] = df['ID'].str.replace('[^0-9]', '', regex=True).astype('int64')
Run Code Online (Sandbox Code Playgroud)
然后输入
0 4806105017087
1 4806105017087
2 CN414149
Name: ID, dtype: object
Run Code Online (Sandbox Code Playgroud)
转换成
0 4806105017087
1 4806105017087
2 414149
Name: ID, dtype: int64
Run Code Online (Sandbox Code Playgroud)