Search code examples
pythonpandasdataframematrixdatatable

How can I transform multiple columns in a table to list


How can I transform Tab 1 to Tab2

transform Tab1 to Tab2

df = pd.DataFrame({'A': [3, 5], 'B': [4, 6], 'Z': [6, 8]}, index=[1, 100])

I suppose pandas df.melt might help, but I'm not sure


Solution

  • You can flatten your dataframe and manipulate index to get expected output:

    out = (df.unstack().sort_index(level=1)
             .set_axis([f'{j}{i}' for i in df.index for j in df.columns])
             .rename_axis('var').rename('val').reset_index())
    

    Output:

    >>> out
        var  val
    0    A1    3
    1    B1    4
    2    Z1    6
    3  A100    5
    4  B100    6
    5  Z100    8