How do I change or access pandas MultiIndex column headers?

后端 未结 2 1435
独厮守ぢ
独厮守ぢ 2021-01-06 20:35

I have the following Pandas DataFrame, but am having trouble updating a column header value, or easily accessing the header values (for example, for plotting a time at the (

2条回答
  •  温柔的废话
    2021-01-06 21:33

    You access MultiIndex via tuples. For example:

    df.loc[:, ('id0', 66, 110)]
    

    However, you may want to access via lon/lat without specifying id or maybe you'll have multiple ids. In that case, you can do 2 things.

    First, use pd.IndexSlice which allows for useful MultiIndex slicing:

    df.loc[:, pd.IndexSlice[:, 66, 110]]
    

    Second:

    df.stack(0).loc[:, (66, 110)].dropna().unstack()
    

    Which is messier, but might be useful.

    Finally, the last thing you mentioned. For a specific row with lon/lat.

    df.loc[2014, pd.IndexSlice[:, 66, 110]]
    

提交回复
热议问题