Pandas get_level_values showed surprise… here is a solution to the problem.
Pandas get_level_values showed surprise
I have a multi-index like this in my data frame:
x = pd. MultiIndex(levels=[['a', 'b', 'c'], ['2014.12.31', 'd', 'e', '2015.12.31']],
labels=[[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]],
names=['proj', 0])
x.get_level_values(0)
x.get_level_values(1)
I hope get_level_values(0) and get_level_values(1)
give me different results. But they didn’t. Is this a bug?
However, x.get_level_values(‘proj'
) and x.get_level_values(0)
give the results I expect. Why? Can someone explain? Thank you.
Solution
You have two index levels, which you can get by name or integer index. The index level of integer index 0
has the name proj
, a string. The index level of integer index 1
has the name 0
, an integer.
When you call get_level_values
(level), pandas
first searches the index level by name. So, in your case, the call get_level_values(0) resolves to the second level of the name 0
, while get_level_values(
1)
resolves to the same level, but in this case integer index 1
.