【问题标题】:Python Pandas dropping Non numerical rows from columnsPython Pandas 从列中删除非数字行
【发布时间】:2016-04-13 16:19:58
【问题描述】:

我有一个数据框,想删除Score列中的非数字行

import pandas as pd

df=pd.DataFrame({
'Score': [4.0,6,'3 1/3',7,'43a'],
'Foo': ['Nis','and stimpy','d','cab','abba'],
'Faggio':[0,1,0,1,0]
})

我想要的结果应该是这样的:

   Faggio         Foo  Score
0       0         Nis      4
1       1  and stimpy      6
3       1         cab      7

我试过了:

ds=df[df['Score'].apply(lambda x: str(x).isnumeric())]

print(ds)

ds2=df[df['Score'].apply(lambda x: str(x).isdigit())]

print(ds2)

但他们都用浮动擦除了列。

【问题讨论】:

    标签: python pandas filtering


    【解决方案1】:

    我认为您需要添加isnull 来检查NaN 值,因为如果不是数字,您的函数会返回NaN。更好更快的是使用text method str.isnumeric()str.isdigit()boolean indexing

    print df['Score'].str.isnumeric()
    0      NaN
    1      NaN
    2    False
    3      NaN
    4    False
    Name: Score, dtype: object
    
    print df['Score'].str.isnumeric().isnull()
    0     True
    1     True
    2    False
    3     True
    4    False
    Name: Score, dtype: bool
    
    print df[df['Score'].str.isnumeric().isnull()]
       Faggio         Foo Score
    0       0         Nis     4
    1       1  and stimpy     6
    3       1         cab     7
    
    print df[df['Score'].str.isdigit().isnull()]
       Faggio         Foo Score
    0       0         Nis     4
    1       1  and stimpy     6
    3       1         cab     7
    

    to_numericnotnull 的类似解决方案:

    print df[pd.to_numeric(df['Score'], errors='coerce').notnull()]
       Faggio         Foo Score
    0       0         Nis     4
    1       1  and stimpy     6
    3       1         cab     7
    

    【讨论】:

    • 不是在示例中,而是在我的真实数据中,我会收到此错误“只能使用带有字符串值的 .str 访问器,在 pandas 中使用 np.object_ dtype”
    • 没问题,你可以添加强制转换到字符串 - df['Score'].astype(str).str.isnumeric()
    • 谢谢 我不记得你可以强制数据类型
    • 好的,我尝试添加类似的解决方案。谢谢你的接受。如果你愿意,你也可以投票。谢谢。
    • 有趣的是,当错误没有被强制时,一些 csv 表都是空白的。所以我认为df[pd.to_numeric(df['Score'], errors='coerce').notnull()]是最好的解决方案
    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 2016-07-20
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多