The Python Oracle

record the location of a conditional entry in pandas

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Music Box Puzzles

--

Chapters
00:00 Record The Location Of A Conditional Entry In Pandas
00:39 Accepted Answer Score 3
01:15 Answer 2 Score 1
01:24 Thank you

--

Full question
https://stackoverflow.com/questions/5240...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas

#avk47



ACCEPTED ANSWER

Score 3


Setup

df = pd.DataFrame(np.nan, range(54, 62), [*'ABCDEFGHIJ'])
df.at[56, 'G'] = 3
df.at[61, 'G'] = 2

any with axis=1

df.index[df.notna().any(1)]

Int64Index([56, 61], dtype='int64')

Print

print(*df.index[df.notna().any(1)], sep='\n')

56
61

More Generally

numpy.where

i, j = np.where(df.notna())
print(*zip(df.index[i], df.columns[j]), sep='\n')

(56, 'G')
(61, 'G')

stack

By default, stack drops null values

print(*df.stack().index.values, sep='\n')

(56, 'G')
(61, 'G')



ANSWER 2

Score 1


Using notnull return Boolean , then sum and slice with the index

df.index[df.notnull().sum(1).nonzero()]
Out[646]: Int64Index([56, 61], dtype='int64')