search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

Creating a MultiIndex DataFrame in Pandas

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Using list of tuples

To create a MultiIndex DataFrame in Pandas, we first need to create a `MultiIndex` object:

``` index = [("A", "alice"), ("A", "bob"), ("A", "cathy"), ("B", "david"), ("B", "eric")]multi_index = pd.MultiIndex.from_tuples(index)multi_index MultiIndex([('A', 'alice'), ('A', 'bob'), ('A', 'cathy'), ('B', 'david'), ('B', 'eric')]) ```

To create a MultiIndex DataFrame, pass `multi_index` directly into the DataFrame constructor:

``` df = pd.DataFrame({"a":[2,3,4,5,6]}, index=multi_index)df aA alice 2 bob 3 cathy 4B david 5 eric 6 ```

Using arrays

To create a Multi-Index from arrays:

``` numbers = [3,3,4]letters = ["A","B","C"]multi_index = pd.MultiIndex.from_arrays([numbers, letters])multi_index MultiIndex([(3, 'A'), (3, 'B'), (4, 'C')]) ```

To create a MultiIndex DataFrame, pass `multi_index` directly into the DataFrame constructor:

``` df = pd.DataFrame({"a":range(3)}, index=multi_index)df a3 A 0 B 14 C 2 ```

Using Cartesian products

To create a MultiIndex using the Cartesian product of two lists:

``` numbers = [3,4,5]letters = ["A","B"]multi_index = pd.MultiIndex.from_product([numbers, letters])multi_index MultiIndex([(3, 'A'), (3, 'B'), (4, 'A'), (4, 'B'), (5, 'A'), (5, 'B')]) ```

To create a MultiIndex DataFrame, pass `multi_index` directly into the DataFrame constructor:

``` df = pd.DataFrame({"a":range(6)}, index=multi_index)df a3 A 0 B 14 A 2 B 35 A 4 B 5 ```
Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!