Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading