I have a DataFrame made of boolean values. What I want is to check whether all entries are True
by applying some function that simply outputs True
or False
after looking at each individual entry. Is there an easy or elegant way to do this?
And more generally speaking, say I have some DataFrame and I want to apply a function to the entries and output a single value (eg sum all the elements up, or take the product of all the elements).Is there some native way to create a function of the form
def f(df):
return single_value(df)
I have seen plenty of methods that subject DataFrame entries to functions, but they all return a DataFrame (most of the time changing it in place). A mathematical example of what I want would be a vector norm since it maps vectors (series in pds) to positive real values.
If you want to check whether the entire dataframe contains only True
boolean values then all you need is
df.eq(True).all()
and the output will be a Series
that indicates whether each column has True
values. For instance,
>>> import pandas as pd
>>> df = pd.DataFrame({'col1': [True, True], 'col2': [True, False], 'col3': [True, None]})
>>> df.eq(True).all()
col1 True
col2 False
col3 False
dtype: bool
Now if you want the output to be a single boolean value then you can apply all()
on the above:
>>> df.eq(True).all().all()
False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.