1

What I want to do but argmax only gives me the first value that is True:

Se = pd.Series(np.arange(6), index=list("abcdef"))
#a    0
#b    1
#c    2
#d    3
#e    4
#f    5
#dtype: int64

mask = (Se % 2 == 0)
#a     True
#b    False
#c     True
#d    False
#e     True
#f    False
#dtype: bool

mask.argmax()
#'a'

What I have to do instead:

Se[mask].index
# Index(['a', 'c', 'e'], dtype='object')

This isn't too inconvenient but I have to instantiate the Series first which reduces my productivity. It would be nice to be able to do this:

(pd.Series(np.arange(6), index=list("abcdef")) % 2 == 0).argmax()

My question is: How can I do this using argmax? If this can't be done w/ argmax, could I do this w/ a different function in pandas?

O.rka
  • 29,847
  • 68
  • 194
  • 309

2 Answers2

2

You can use compress:

idx = pd.Series(np.arange(6), index=list("abcdef")).compress(lambda x: x % 2 == 0).index

The resulting output:

Index(['a', 'c', 'e'], dtype='object')
root
  • 32,715
  • 6
  • 74
  • 87
0

In the latest pandas version, you can directly pass the filter function to [] or .loc[]:

Se[lambda x: x%2 == 0].index  # or Se.loc[lambda x: x%2 == 0].index
# Index([u'a', u'c', u'e'], dtype='object')
Psidom
  • 209,562
  • 33
  • 339
  • 356