Inconsistent behavior of any(df == value) on pandas dataframe
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: Lost Jungle Looping
--
Chapters
00:00 Question
01:21 Accepted answer (Score 6)
02:25 Answer 2 (Score 3)
02:42 Answer 3 (Score 2)
02:56 Thank you
--
Full question
https://stackoverflow.com/questions/4604...
Answer 1 links:
[DataFrame.any]: http://pandas.pydata.org/pandas-docs/sta...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #any
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping
--
Chapters
00:00 Question
01:21 Accepted answer (Score 6)
02:25 Answer 2 (Score 3)
02:42 Answer 3 (Score 2)
02:56 Thank you
--
Full question
https://stackoverflow.com/questions/4604...
Answer 1 links:
[DataFrame.any]: http://pandas.pydata.org/pandas-docs/sta...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #any
#avk47
ACCEPTED ANSWER
Score 6
You need to use pandas built in any instead of any from base Python:
df1.eq(1).any().any()
# True
df2.eq(1).any().any()
# True
When using any from python, it treats the data frame as an iterable/dictionary and thus only check the column names, without looking at the values of the data frame; If you simply loop through df1 and df2, you can see it only returns the column names, which is how a dictionary behaves; Since df1 contains column names of 0 and 1, any([0,1]) will return True; df2, on the other hand, contains only one column of [0], any([0]) returns False. So any(df == 1) is somewhat equivalent to any(df) or any(df.columns):
[x for x in df1]
# [0, 1]
[x for x in df2]
# [0]
ANSWER 2
Score 3
In pandas better use DataFrame.any.
Numpy solutions:
print ((df1 == 1).values.any())
True
print ((df2 == 1).values.any())
True
ANSWER 3
Score 2
You need to use (df2 == 1).any() instead