I've seen the other comments on here about how you can correctly sort the columns when the pivot() makes the date the column name. What I haven't seen is how to convert those dates to a format I want after the sorting.
Here is my example. I have data that looks like this:
| category | date | value1 | value2 |
|---|---|---|---|
| a | 12/1/2018 | 1 | 25 |
| a | 1/1/2019 | 2 | 26 |
| a | 2/1/2019 | 3 | 27 |
| b | 12/1/2018 | 4 | 28 |
| b | 1/1/2019 | 5 | 29 |
| b | 2/1/2019 | 6 | 30 |
| c | 12/1/2018 | 7 | 31 |
| c | 1/1/2019 | 8 | 32 |
| c | 2/1/2019 | 9 | 33 |
What I want is something like this:
| category | value | Dec-18 | Jan-19 | Feb-19 |
|---|---|---|---|---|
| a | value1 | 1 | 2 | 3 |
| a | value2 | 25 | 26 | 27 |
| b | value1 | 4 | 5 | 6 |
| b | value2 | 28 | 29 | 30 |
| c | value1 | 7 | 8 | 9 |
| c | value2 | 31 | 32 | 33 |
I have figured out how to get pivot to do one value at a time, and to sort the dates as long as I don't try to format them. But pivot is converting those dates to text so I can't change the format anymore.
This is what I have so far:
#df['date'] = pd.to_datetime(df.date).dt.strftime('%b-%y') final = df.pivot(index='category', columns='date', values='value1')
If I do the date formatting first, it sorts incorrectly. I also tried pivot_table but it won't let me set aggfunc=None.
The date formatting has to be dynamic aka every month the date range is going to be different (last 12 months), so I don't want to hard-code the date.
Thanks!