Reputation: 5759
If I have a multiindexed dataframe, how can i get the information in just one of the indexes?
If my df is this:
first second
bar one 0.469112
two -0.282863
baz one -1.509059
two -1.135632
foo one 1.212112
two -0.173215
qux one 0.119209
two -1.044236
I would like a list of the values in index first
. I'm used to doing something like this:
df.index.tolist()
which returns:
['bar','baz','foo','qux']
Upvotes: 1
Views: 47
Reputation: 323226
Data from jpp
df.index.levels[0]
Out[412]: Index(['A', 'X'], dtype='object', name='idx1')
Update :
[x[0] for x in df.index.tolist()]
Out[417]: ['A', 'A', 'X', 'X']
Upvotes: 3
Reputation: 164673
You can use pd.Index.get_level_values
. Here's a demo:
df = pd.DataFrame([['A', 'B', 1], ['A', 'C', 2], ['X', 'Y', 3], ['X', 'Z', '4']],
columns=['idx1', 'idx2', 'value'])
df = df.set_index(['idx1', 'idx2'])
res = df.index.get_level_values(0).tolist()
['A', 'A', 'X', 'X']
Upvotes: 4