[Python] How do I create a multi-index dataframe from tuples/lists

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    I want to create (for example) a small multi-index dataframe with 3 level index and one column of values. There will only be a handful of rows.

    Value
    Category Sub Category Sub Sub Category
    Machine Car Sedan 10
    Machine Bike 2 wheel 5
    Machine Bike 3 wheel 4
    Animal Donkey Big 2

    A requirement is that the data has to be easy to enter, a row at a time, from left to right (not top to bottom), so my first step is to make a list of lists.

    Then I can use DataFrame method and then the set-index method like this:

    data=[["Machine","Car","Sedan",10], ["Machine","Bike","2 Wheel",5], ["Machine","Bike","3 Wheel",4], ["Animal","Donkey","Big",2]]
    column_names=["Category","Sub Category","Sub Sub Category","Value"]
    df=pd.DataFrame(data,columns=column_names)
    df.set_index(["Category","Sub Category","Sub Sub Category"])


    But is there a way to make the multi-index DataFrame directly from a list, or something like it?

    Continue reading...

Compartilhe esta Página