The Python Oracle

record the location of a conditional entry in pandas

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: RPG Blues Looping

--

Chapters
00:00 Question
00:56 Accepted answer (Score 3)
01:45 Answer 2 (Score 1)
02:01 Thank you

--

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

Question links:
[image]: https://i.stack.imgur.com/HYR6q.png

--

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