Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if dataframe is of boolean type pandas

I have a pandas DataFrame as below:

In [108]: df1
Out[108]: 
                         v
t                         
2014-02-21 10:30:43  False
2014-02-21 10:31:34  False
2014-02-21 10:32:25  False
2014-02-21 10:33:17  False
2014-02-21 10:34:09  False
2014-02-21 10:35:00  False
2014-02-21 10:35:51  False

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

In [109]: print isinstance(df1, bool)
False

**It should return **True****

How can I do this?

Reference: check if variable is dataframe

like image 535
curlyreggie Avatar asked Feb 24 '14 08:02

curlyreggie


People also ask

How do you check boolean in a DataFrame?

The bool() method returns a boolean value, True or False, reflecting the value of the DataFrame. This method will only work if the DataFrame has only 1 value, and that value must be either True or False, otherwise the bool() method will return an error.

How do I know if a DataFrame is true?

all() method checks whether all elements are True, potentially over an axis. It returns True if all elements within a series or along a Dataframe axis are non-zero, not-empty or not-False.

What does .ANY do in pandas?

Definition and Usage. The any() method returns one value for each column, True if ANY value in that column is True, otherwise False. By specifying the column axis ( axis='columns' ), the all() method returns True if ANY value in that axis is True.

What is the type of a DataFrame?

Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects.


1 Answers

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')

So 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
like image 176
EdChum Avatar answered Sep 21 '22 22:09

EdChum