如何在python中删除错误类型的行?

fre*_*rog 3 python type-conversion dataframe pandas

我有一个这样的数据框:

import pandas as pd
test_df = pd.DataFrame({'foo':['1','2','92#']})
test_df

    foo
0   1
1   2
2   92#
Run Code Online (Sandbox Code Playgroud)

我想将类型转换为int64:

test_df.foo.astype('int64')
Run Code Online (Sandbox Code Playgroud)

但我收到错误消息,因为'92#'无法转换为int64:

ValueError:基数为10的int()的无效文字:'92#'

所以我想删除所有无法转换为int64的行,并得到我的结果:

    foo
0   1
1   2
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 7

如果你想要一个适用于数据帧作为一个整体的解决方案,呼叫pd.to_numeric通过apply,并使用结果屏蔽砸行:

test_df[test_df.apply(pd.to_numeric, errors='coerce').notna()].dropna()

  foo
0   1
1   2
Run Code Online (Sandbox Code Playgroud)

这不会修改其test_df值.OTOH,如果你想在转换值时删除行,你的解决方案简化了:

test_df.apply(pd.to_numeric, errors='coerce').dropna()

   foo
0  1.0
1  2.0
Run Code Online (Sandbox Code Playgroud)

.astype(int)如果您想要结果类型转换,请在最后添加一个调用int64.