Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

python - Function of pandas DataFrame that creates single value output

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 Trueor Falseafter 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 (e.g. 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.

question from:https://stackoverflow.com/questions/66061797/function-of-pandas-dataframe-that-creates-single-value-output

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  • eq() can be used to perform element-wise comparisons
  • all() is used to check whether all elements are True, potentially over an axis.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...