【问题标题】:check all items in csv column except one [python pandas]检查 csv 列中的所有项目,除了一个 [python pandas]
【发布时间】:2020-11-12 12:24:41
【问题描述】:

我试图弄清楚如何检查一整列以验证所有值都是整数,除了一个,使用 python pandas。一个行名总是有一个浮点数。 CSV 示例:

name, num
random1,2
random2,3
random3,2.89
random4,1
random5,3.45

在这个例子中,假设 'random3 的 num 永远是一个浮点数。因此,random5 也是一个浮点数,这意味着程序应该向终端打印一个错误,告诉用户这一点。

【问题讨论】:

    标签: python python-3.x pandas csv


    【解决方案1】:

    试试这个:

    if len(df.num.apply(type) == float) >= 2:
     print(f"Ups!. There are {len(df.num.apply(type) == float)} float numbers in the column") float numbers in the column")
    

    各组件说明:

    df.num.apply(type) # Generates a series showing the amount of rows per class
    (df.num.apply(type) == float) # Derived series sorting only the values with the defined class.
    

    【讨论】:

    • 您的代码不符合 OP 的要求。 len(df.num.apply(type)==float) 返回5,这是系列的长度,而不是系列中的浮点数。
    • @Craig 确保您的数据设置正确。首先应用 df.num.apply(type) 以检查数据帧的所有类型,然后应用过滤器。
    • 我无法重现您的结果,请将您的测试数据添加到答案中。
    • @Craig。似乎您的 DataFrame 转换了浮点数中的所有整数。这就是您的结果为 5 的原因。您没有正确设置 OP 所示的 DataFrame。
    【解决方案2】:

    当 pandas read_csv() 函数将 CSV 文件加载到数据框中时,它会将 float dtype 分配给任何包含 float 和 integer 值的列。要测试列的元素是否可以精确地表示为整数,可以使用How to check if float pandas column contains only integer numbers?的答案中描述的浮点数的.is_integer()方法

    在你的情况下,你想验证你在列中只有一个浮点数,所以这样做:

    import pandas as pd
    df = pd.DataFrame({'name':[f"random{i}" for i in range(1,6)], 'num':[2, 3, 2.89, 1, 3.45]})
    
    if sum(~df.num.apply(float.is_integer)) != 1:
        print("Error, the data column contains the wrong number of floats!")
    

    如果该列可能仅包含整数,则该列将具有整数 dtype,并且上述代码将导致错误。你可以发现错误,或者你也可以测试这种情况:

    from pandas.api.types import is_float_dtype
    
    if not is_float_dtype(df.num) or sum(~df.num.apply(float.is_integer)) != 1:
        print("Error, the data column contains the wrong number of floats!")
    

    【讨论】:

    • 您在定义数据框时错过了结尾括号
    猜你喜欢
    • 2020-03-28
    • 2018-07-07
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2014-06-25
    • 1970-01-01
    相关资源
    最近更新 更多