curlyreggie
curlyreggie

Reputation: 1530

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

Upvotes: 9

Views: 25374

Answers (3)

c_drik
c_drik

Reputation: 73

Use is_bool_dtype :

from pandas.api.types import is_bool_dtype
...
is_bool_dtype(df["a"])

Reference : https://pandas.pydata.org/docs/reference/api/pandas.api.types.is_bool_dtype.html

Upvotes: 0

EdChum
EdChum

Reputation: 394041

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

Upvotes: 10

Ynjxsjmh
Ynjxsjmh

Reputation: 30032

To get the dtype of a specific column, you have two ways:

  1. Use DataFrame.dtypes which returns a Series whose index is the column header.
$ df.dtypes.loc['v']

bool
  1. Use Series.dtype or Series.dtypes to get the dtype of a column. Internally Series.dtypes calls Series.dtype to get the result, so they are the same.
$ df['v'].dtype

bool

$ df['v'].dtypes

bool

All of the results return the same type

$ type(df.dtypes.loc['v'])

<class 'numpy.dtype[bool_]'>

$ type(df['v'].dtype)

<class 'numpy.dtype[bool_]'>

To check if it is a bool type also has multiple ways

$ df['v'].dtype == 'bool'

True

$ np.issubdtype(df['v'].dtype, bool)

True

$ df['v'].dtype.type is np.bool_

True

You can also select the columns with specific types with DataFrame.select_dtypes

$ df.select_dtypes('bool')

       v
0  False
1  False
2  False

Upvotes: 1

Related Questions