Search code examples
pandasdataframeindexingmulti-index

pandas multiindex select one header value according to another header and a level


I have this dataframe with multiple headers

name,   00590BL,    01090BL,    01100MS,    02200MS
lat,    613297, 626278, 626323, 616720
long,   5185127,    5188418,    5188431,    5181393
elv,    1833,   1915,   1915,   1499
1956-01-01, 1,  2,  2,  -2
1956-01-02, 2,  3,  3,  -1
1956-01-03, 3,  4,  4,  0
1956-01-04, 4,  5,  5,  1
1956-01-05, 5,  6,  6,  2

I read it as

dfr      =  pd.read_csv(f_name,
                            skiprows     = 0,
                            header       = [0,1,2,3], 
                            index_col    = 0,
                            parse_dates  = True
                            )

I would like to get the value of the first level according to the level 0 value. I try to make myself clear. I would like to select the column '01090BL' (header level 0) and then I would like to get the value corresponding to the level 1 (named 0).

I have try the following:

dfr[['00590BL']['lat']]

a sort of matrix between headers. I get an error. I thing that I need a glue on multiindex handling.

I expect a sort of this:

value = dfr[['00590BL']]['lat']

with value=613297

Thanks


Solution

  • Use MultiIndex.get_level_values:

    dfr['00590BL'].columns.get_level_values('lat')[0]
    

    Output: '613297'.

    Make sure than you don't have spaces when reading the data, you might need to add the sep=',\s*', engine='python' parameters in read_csv.