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
464 views
in Technique[技术] by (71.8m points)

python - Getting a list of indices where pandas boolean series is True

I have a pandas series with boolean entries. I would like to get a list of indices where the values are True.

For example the input pd.Series([True, False, True, True, False, False, False, True])

should yield the output [0,2,3,7].

I can do it with a list comprehension, but is there something cleaner or faster?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Using Boolean Indexing

>>> s = pd.Series([True, False, True, True, False, False, False, True])
>>> s[s].index
Int64Index([0, 2, 3, 7], dtype='int64')

If need a np.array object, get the .values

>>> s[s].index.values
array([0, 2, 3, 7])

Using np.nonzero

>>> np.nonzero(s)
(array([0, 2, 3, 7]),)

Using np.flatnonzero

>>> np.flatnonzero(s)
array([0, 2, 3, 7])

Using np.where

>>> np.where(s)[0]
array([0, 2, 3, 7])

Using np.argwhere

>>> np.argwhere(s).ravel()
array([0, 2, 3, 7])

Using pd.Series.index

>>> s.index[s]
array([0, 2, 3, 7])

Using python's built-in filter

>>> [*filter(s.get, s.index)]
[0, 2, 3, 7]

Using list comprehension

>>> [i for i in s.index if s[i]]
[0, 2, 3, 7]

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

...