pythonpandasdataframe

Python Pandas Dataframe Row name Change


How can I replace the first index 0 with "Color" and 1 with "Size"?

import pandas as pd
clothes = {"shirt": ["red", "M"], "sweater": ["yellow", "L"], "jacket": ["black", "L"]}

# pd.DataFrame.from_dict(clothes)
df = pd.DataFrame.from_dict(clothes)
df

I tried like this but nothing changes. The output shows index name as an error

df = pd.DataFrame.from_dict(clothes, index = ['color', 'size'])

Solution

  • don't use from_dict, but the DataFrame constructor directly:

    df = pd.DataFrame(clothes, index=['color', 'size'])
    

    If the DataFrame is already existing, set_axis:

    df = pd.DataFrame(clothes)
    
    df = df.set_axis(['color', 'size'])
    

    output:

          shirt sweater jacket
    color   red  yellow  black
    size      M       L      L