Search code examples
pythonpandasdataframemulti-index

TypeError: sequence item 1: expected str instance, int found when flattening MultiIndex pandas column


I have previously asked a similar question - pandas - Reorganize a multi-row & multi-column DataFrame into single-row & multi-column DataFrame, however, when I use the provided solution:

v = df.unstack().to_frame().sort_index(level=1).T
v.columns = v.columns.map('_'.join)

on this following DataFrame (with switched column & row values compared to the example in the mentioned answer),

index      A          B       C
    1  Apple     Orange   Grape
    2    Car      Truck   Plane
    3  House  Apartment  Garage

However, this line: v.columns = v.columns.map('_'.join) throws the following Error: TypeError: sequence item 1: expected str instance, int found

Is there any way to get the following output?

     A_1     A_2    A_3  B_1    B_2    B_3    C_1        C_2     C_3
0  Apple  Orange  Grape  Car  Truck  Plane  House  Apartment  Garage

Thank you.


Solution

  • Happens when your headers are integeral. Try using .format instead:

    v = df.unstack().to_frame().T
    v.columns = v.columns.map('{0[0]}_{0[1]}'.format)
    

    print(v)
         A_1  A_2    A_3     B_1    B_2        B_3    C_1    C_2     C_3
    0  Apple  Car  House  Orange  Truck  Apartment  Grape  Plane  Garage