How to check if float pandas column contains only integer numbers?

后端 未结 4 649
挽巷
挽巷 2020-12-15 18:07

I have a dataframe

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

How to make sure that the numbers in v

4条回答
  •  北海茫月
    2020-12-15 18:57

    If you want to check multiple float columns in your dataframe, you can do the following:

    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)
    

    Keep in mind that a float column, containing all integers will not get selected if it has np.NaN values. To cast float columns with missing values to integer, you need to fill/remove missing values, for example, with median imputation:

    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)
    

提交回复
热议问题