Pandas
keyboard_arrow_down 655 guides
chevron_leftMulti-index Operations Cookbook
check_circle
Mark as learned thumb_up
0
thumb_down
0
chat_bubble_outline
0
Comment auto_stories Bi-column layout
settings
Setting multi-index using two columns of a DataFrame in Pandas
schedule Aug 12, 2023
Last updated local_offer
Tags Python●Pandas
tocTable of Contents
expand_more Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!
Start your free 7-days trial now!
To set a multi-index to a DataFrame using two of its columns, use the DataFrame's set_index(~)
method.
Examples
Consider the following DataFrame:
index = [("A", "alice"), ("A", "bob"),("A", "cathy"), ("B", "david"),("B", "eric")]df = pd.DataFrame({"group":["A","A","A","B","B"],"name":["alice","bob","cathy","david","eric"],"age":[2,3,4,5,6]})df
group name age0 A alice 21 A bob 32 A cathy 43 B david 54 B eric 6
To set columns group
and name
as the multi-index of df
:
df
group name ageA alice 2 bob 3 cathy 4B david 5 eric 6
Here, we have 2 indexes, and by default, the column labels (i.e. group
and name
) are assigned as the name of the 2 new indexes.
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!