pandas how to check dtype for all columns in a dataframe?

后端 未结 3 643
一生所求
一生所求 2021-01-30 00:05

It seems that dtype only work for pandas.DataFrame.Series, right? Is there a function to display data types of all columns at once?

3条回答
  •  佛祖请我去吃肉
    2021-01-30 00:32

    To go one step further, I assume you want to do something with these dtypes. df.dtypes.to_dict() comes in handy.

    my_type = 'float64' #<---
    
    dtypes = dataframe.dtypes.to_dict()
    
    for col_nam, typ in dtypes.items():
        if (typ != my_type): #<---
            raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
    

    You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype will succeed when .dtype==np.float64.

提交回复
热议问题