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

How can I reshape a table with Pandas

I need to reshape a single column table with the next format:

Year foo bar baz
1999 10 30 20

to the format:
| Category | value |
|—–|——-|
| foo | 10 |
| bar | 30 |
| baz | 20 |

I kinda know how to use pandas pivot and pandas melt, but for some reason, it’s not working with my table.
I made the table extracting a single row from a bigger one containing more years.

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

>Solution :

Simply calling pd.melt on your data works for me, with pandas version 1.4.3

df = pd.DataFrame({
    "Year": [1999],
    "foo": [10],
    "bar": [30],
    "baz": [20],
})
pd.melt(df)

Outputs:

  variable  value
0     Year   1999
1      foo     10
2      bar     30
3      baz     20
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