【问题标题】:how to drop rows of wrong type in python?如何在python中删除错误类型的行?
【发布时间】:2018-10-20 10:46:41
【问题描述】:

我有一个这样的数据框:

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

    foo
0   1
1   2
2   92#

我想把类型转成int64:

test_df.foo.astype('int64')

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

ValueError: int() 以 10 为底的无效文字:'92#'

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

    foo
0   1
1   2

【问题讨论】:

    标签: python pandas dataframe type-conversion


    【解决方案1】:

    如果您想要一个适用于整个数据帧的解决方案,请调用pd.to_numericapply,并使用生成的掩码删除行:

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

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

    test_df.apply(pd.to_numeric, errors='coerce').dropna()
    
       foo
    0  1.0
    1  2.0
    

    如果您希望将结果类型转换为int64,请在末尾添加.astype(int) 调用。

    【讨论】:

    • 不知道.notna 应该多关注最新消息部分+1
    • @EdChum 啊,是的,这是 0.22 的事情。虽然我应该提到它在向后兼容 Pandas 代码方面存在问题,并且启动速度比 notnull 慢几微秒。熊猫开发者很奇怪...... xD
    猜你喜欢
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 2017-12-18
    • 1970-01-01
    相关资源
    最近更新 更多