Pandas pivot to explode columns and fill values?
Question:
I have a Pandas dataframe like so
movie, week, sales
-----, ----, ------
1, 1, 100
...
1, 52, 200
2, 1, 500,
...
What I actually want it to look like is
movie, week_1, ... week_52,
1, 1, 200
2, 1, 500
So what’s effectively happened is there is now one row per movie and one column per week and the value of df[movie, week]
equals the sales of that movie on that week.
I’ve tried df.transpose()
and df.pivot(columns=['week', 'sales'])
but neither is accomplishing the intended effect.
What the Pandas way to do this?
Answers:
You can achieve that in pandas using the following:
df = df.pivot_table(index='movie', columns='week', values='sales')
If you want to have the columns named as week_1
, week_2
… you can also use:
df.columns = [f'week_{x}' for x in df.columns]
I have a Pandas dataframe like so
movie, week, sales
-----, ----, ------
1, 1, 100
...
1, 52, 200
2, 1, 500,
...
What I actually want it to look like is
movie, week_1, ... week_52,
1, 1, 200
2, 1, 500
So what’s effectively happened is there is now one row per movie and one column per week and the value of df[movie, week]
equals the sales of that movie on that week.
I’ve tried df.transpose()
and df.pivot(columns=['week', 'sales'])
but neither is accomplishing the intended effect.
What the Pandas way to do this?
You can achieve that in pandas using the following:
df = df.pivot_table(index='movie', columns='week', values='sales')
If you want to have the columns named as week_1
, week_2
… you can also use:
df.columns = [f'week_{x}' for x in df.columns]