Search code examples
pandaspivotmelt

Pandas: Pivot a table using the column names as variables


I have a dataset in which each column represent a different measurement for a specific parameter. The parameter name is the column name.

I have the following sample code:

df=pd.DataFrame({'A': (1,2), 'B':(3,4)})
display(df)
    A   B
0   1   3
1   2   4

What I would like to obtain is a table like this

    Parameter   value
0   A           1
1   A           2
2   B           3
3   B           4

I've seen in the documentation that there are pivot_table and melt functions, but I do not know how to apply them in this case.


Solution

  • Pandas melt function is useful to massage a DataFrame into a format where one or more columns are identifier variables (id_vars), while all other columns are considered measured variables (value_vars). For more information, you can check out the docs Pandas Melt

    • "id_vars" accepts a list that should be used as an index when the DataFrame is combined.
    • "value_vars" accepts a list that should be used as a value when the DataFrame is combined.
       import pandas as pd
       df = pd.DataFrame({'A': (1,2), 'B':(3,4)})
       df = df.melt(value_vars = df.columns.to_list())
       print(df.head())
    

    Output would look like this

      variable  value
    0        A      1
    1        A      2
    2        B      3
    3        B      4