check if dataframe is of boolean type pandas
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 Question
00:45 Accepted answer (Score 8)
01:48 Thank you
--
Full question
https://stackoverflow.com/questions/2198...
Question links:
[check if variable is dataframe]: https://stackoverflow.com/questions/1480...
Accepted answer links:
[numpy.dtype]: http://docs.scipy.org/doc/numpy/referenc...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Luau
--
Chapters
00:00 Question
00:45 Accepted answer (Score 8)
01:48 Thank you
--
Full question
https://stackoverflow.com/questions/2198...
Question links:
[check if variable is dataframe]: https://stackoverflow.com/questions/1480...
Accepted answer links:
[numpy.dtype]: http://docs.scipy.org/doc/numpy/referenc...
--
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:
- Use
DataFrame.dtypeswhich returns a Series whose index is the column header.
$ df.dtypes.loc['v']
bool
- Use
Series.dtypeorSeries.dtypesto get the dtype of a column. InternallySeries.dtypescallsSeries.dtypeto 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