Search code examples
pythonpandasmulti-index

How to do positional indexing on a pandas series with multi-index


I have a series

s

card  city
c1    t1      0.500000
      t2      0.250000
      t3      0.250000
c2    t2      0.666667
      t1      0.333333
Name: city, dtype: float64

I want to get the top (or n-th) city entry for each card. I essentially want something of s.iloc[:,n] type i.e., a way to do positional indexing into a pandas series with multi-index. I am using pandas-1.3.2.


Solution

  • You can use groupby.head:

    s.groupby(level='card').head(1)
    
    card  city
    c1    t1      0.500000
    c2    t2      0.666667
    Name: city2, dtype: float64
    

    To get the n-th entry per group, group first and then use iloc in each group. For instance, to get the 2nd entry for each card:

    n = 1
    (s.groupby(level='card', group_keys=False)
      .apply(lambda g: g.iloc[n:n+1]))
    
    card  city
    c1    t2      0.250000
    c2    t1      0.333333
    Name: city2, dtype: float64