The Python Oracle

check if dataframe is of boolean type pandas

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction

--

Chapters
00:00 Check If Dataframe Is Of Boolean Type Pandas
00:32 Accepted Answer Score 10
01:13 Answer 2 Score 1
02:02 Thank you

--

Full question
https://stackoverflow.com/questions/2198...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas #dataframe

#avk47



ACCEPTED ANSWER

Score 10


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



ANSWER 2

Score 1


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