How can I reshape a table with Pandas

Question:

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.

Asked By: Aris

||

Answers:

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
Answered By: Robert Robison

Use pandas.melt :

out = pd.melt(df, value_vars=['foo', 'bar', 'baz']).rename(columns={'variable':'Category'})

print(out)

  Category  value
0      foo     10
1      bar     30
2      baz     20
Answered By: L'Artiste
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.