Reputation: 1905
I want to to get a specific index of a Pandas data frame with a MultiIndex
as a list.
Given the example
import pandas as pd; import numpy as np
np.random.seed(42)
df = pd.DataFrame(np.random.randint(5, size=(5, 4)), columns=list('ABCD'))
df.set_index(['A', 'B'], inplace=True)
in which df
is defined as
C D
A B
3 4 2 4
4 1 2 2
2 4 3 2
4 1 3 1
3 4 0 3
I want to extract
[4 1 4 1 4]
which corresponds to the second index B
. How can this be done?
Upvotes: 0
Views: 105
Reputation: 1905
This solution uses stacking through np.stack()
and slicing:
np.stack(df.index.values, axis=0)[:,1]
Upvotes: 0
Reputation: 323226
Using get_level_values
df.index.get_level_values(level=1).tolist()
Out[1040]: [4, 1, 4, 1, 4]
Or reset_index
df.reset_index(level=1).B.tolist()
Out[1041]: [4, 1, 4, 1, 4]
Upvotes: 4