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.
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
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
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.
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
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