pandasdataframe

check if DataFrame column is boolean type


I have a pandas DataFrame as below:

>>> df
t                        v
2014-02-21 10:30:43  False
2014-02-21 10:31:34  False
2014-02-21 10:32:25  False

>>> df.dtypes
t   str
v   bool

I need to check if the dtype of this dataframe is bool. I tried with:

>>> print('Type is Boolean = ', isinstance(df1, bool) )
Type is Boolean = False

How can I do this?

Source: check if variable is dataframe


Solution

  • You can print the dtypes of the columns:

    In [2]:
    
    import pandas as pd
     
    df = pd.DataFrame({'a':[True,False,False]})
    df
    Out[2]:
           a
    0   True
    1  False
    2  False
    
    [3 rows x 1 columns]
    
    In [3]:
    
    df.dtypes
    
    Out[3]:
    a    bool
    dtype: object
    In [4]:
    
    df.a.dtypes
    Out[4]:
    dtype('bool')
    

    In your case, df1.v.dtypes should print the same output as above

    The other thing to note that isinstance(df, bool) will not work as it is a pandas dataframe or more accurately:

    In [7]:
    
    type(df)
    Out[7]:
    pandas.core.frame.DataFrame
    

    The important thing to note is that dtypes is in fact a numpy.dtype you can do this to compare the name of the type with a string but I think isinstance is clearer and preferable in my opinion:

    In [13]:
    
    df.a.dtypes.name == 'bool'
    Out[13]:
    True