The Unfun Cat
The Unfun Cat

Reputation: 31908

Using multi-indexes as columns

I have a dataframe where the index is a multi-index of start and end values. If these were regular columns, I could just do

df["End"] - df["Start"]

However, since these rows are multi-indexes I get the error KeyError: 'End' when I try this.

I could do a for-loop over the values I get from df.index.get_values() to add each start and end to their own list and make a dataframe from that, but this is very un-pandaish and slow.

Upvotes: 1

Views: 32

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77951

Index.get_level_values will get the index values at a given level.

so, in your case:

df.index.get_level_values('End') - df.index.get_level_values('Start')

Upvotes: 1

Related Questions