0

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?

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

Comments

0

This solution uses stacking through np.stack() and slicing:

np.stack(df.index.values, axis=0)[:,1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.