Home > other >  how to return last index on the multiindex in pandas
how to return last index on the multiindex in pandas

Time:05-24

I want to have a return value from a multiindex. Here is what i mean:

import pandas as pd
import numpy as np

index = pd.MultiIndex.from_product([['2022-05-22', '2022-05-23', '2022-05-24', '2022-05-25'], ['a', 'b', 'c']])
data = pd.Series(np.random.rand(12), index=index)
data.index.names = ['date', 'var']
data

Will result on:

date        var
2022-05-22  a      0.757109
            b      0.149882
            c      0.285188
2022-05-23  a      0.020857
            b      0.274391
            c      0.048735
2022-05-24  a      0.459640
            b      0.585560
            c      0.073415
2022-05-25  a      0.991139
            b      0.681288
            c      0.284437
dtype: float64

If i type: data.index[-1] i will get: ('2022-05-25', 'c')

How to get only 2022-05-25 as a result without the second index? Also how to get 2022-05-24 (the second lowest level 0 index) as a return value?

CodePudding user response:

You can extract the wanted level and keep the unique values:

l = data.index.get_level_values('date').unique()

l[-1]
# '2022-05-25'

l[-2]
# '2022-05-24'

Other approach, unstack:

idx = data.unstack().index

idx[-1]
# '2022-05-25'

idx[-2]
# '2022-05-24'

CodePudding user response:

what happens when you run type(data.index[-1])?

This means you can access this the same way in which you would any other tuple in python.

data.index[-1][0]

  • Related