代码之家  ›  专栏  ›  技术社区  ›  00__00__00

如何检查float pandas列是否只包含整数?

  •  32
  • 00__00__00  · 技术社区  · 8 年前

    我有一个数据框

    df = pd.DataFrame(data=np.arange(10),columns=['v']).astype(float)
    

    如何确保 v 是整数吗? 我非常担心舍入/截断/浮点表示错误

    5 回复  |  直到 8 年前
        1
  •  38
  •   Community Mohan Dere    6 年前

    与比较 astype(int)

    暂时将列转换为 int 并使用进行测试 np.array_equal :

    np.array_equal(df.v, df.v.astype(int))
    True
    

    float.is_integer

    您可以将此python函数与 apply :

    df.v.apply(float.is_integer).all()
    True
    

    或者,使用python的 all 在发电机理解中,对于空间效率:

    all(x.is_integer() for x in df.v)
    True
    
        2
  •  12
  •   scott    6 年前

    以下是一种更简单、可能更快的方法:

    (df[col] % 1  == 0).all()
    

    要忽略空值,请执行以下操作:

    (df[col].fillna(-9999) % 1  == 0).all()
    
        3
  •  7
  •   mgoldwasser    7 年前

    如果要检查数据帧中的多个浮点列,可以执行以下操作:

    col_should_be_int = df.select_dtypes(include=['float']).applymap(float.is_integer).all()
    float_to_int_cols = col_should_be_int[col_should_be_int].index
    df.loc[:, float_to_int_cols] = df.loc[:, float_to_int_cols].astype(int)
    

    请记住,如果包含所有整数的浮点列 np.NaN 价值观要将缺少值的浮点列转换为整数,需要填充/删除缺少的值,例如,使用中值插补:

    float_cols = df.select_dtypes(include=['float'])
    float_cols = float_cols.fillna(float_cols.median().round()) # median imputation
    col_should_be_int = float_cols.applymap(float.is_integer).all()
    float_to_int_cols = col_should_be_int[col_should_be_int].index
    df.loc[:, float_to_int_cols] = float_cols[float_to_int_cols].astype(int)
    
        4
  •  4
  •   ankostis    6 年前

    为了完整性, 熊猫v1.0+ 提供 convert_dtypes() utility ,它(在其他3个转换中)对仅包含整数的所有数据帧列(或序列)执行请求的操作。

    如果要将转换仅限于单个列,可以执行以下操作:

    >>> df.dtypes          # inspect previous dtypes
    v                      float64
    
    >>> df["v"] = df["v"].convert_dtype()
    >>> df.dtypes          # inspect converted dtypes
    v                      Int64
    
        5
  •  1
  •   Nicoolasens    4 年前

    在…上 27 331 625行 它工作得很好。 时间:1.3秒

    df['is_float'] = df[field_fact_qty]!=df[field_fact_qty].astype(int)
    

    这条路走了 时间:4.9秒

    df[field_fact_qty].apply(lambda x : (x.is_integer()))