Pivoting Pandas Dataframes

Python

Creates a new DataFrame that pivots the orders Dataframe so the rows are product IDs, the columns are order dates and the cell values are units sold. Any NAs are filled with 0s.

 1|  units_by_day = orders.groupby(['Order_Date','ProductID'],as_index=False)['units'].sum()
 2|  units_by_day_pivot = units_by_day.pivot(index='ProductID', columns='Order_Date', values='units').reset_index()
 3|  units_by_day_pivot.fillna(0, inplace=True)
Did you find this snippet useful?

Sign up for free to to add this to your code library