Find mixed types in Pandas columns

前端 未结 3 2045
闹比i
闹比i 2020-12-25 15:06

Ever so often I get this warning when parsing data files:

WARNING:py.warnings:/usr/local/python3/miniconda/lib/python3.4/site-
packages/pandas-0.16.0_12_gdcc         


        
3条回答
  •  盖世英雄少女心
    2020-12-25 16:01

    This approach uses pandas.api.types.infer_dtype to find the columns which have mixed dtypes. It was tested with Pandas 1 under Python 3.8.

    Note that this answer has multiple uses of assignment expressions which work only with Python 3.8 or newer. It can however trivially be modified to not use them.

    if mixed_dtypes := {c: dtype for c in df.columns if (dtype := pd.api.types.infer_dtype(df[c])).startswith("mixed")}:
        raise TypeError(f"Dataframe has one more mixed dtypes: {mixed_dtypes}")
    

    This approach doesn't however find a row with the changed dtype.

提交回复
热议问题