-1

I'd like to convert the dates that are in table rows in to table columns. So I'd like to take this output:

Name      | Date     | Consumption
Business A|2021-01-01|12
Business B|2021-01-01|15
Business C|2021-01-01|18
Business A|2021-02-01|10
Business B|2021-02-01|14
Business C|2021-02-01|13
Business A|2021-03-01|23
Business B|2021-03-01|21
Business C|2021-03-01|19

And turn it in to this output:

Name      | Jan-21 | Feb-21 | Mar-21
Business A|12      |10      |23
Business B|15      |14      |21
Business C|18      |13      |19

I'd like to use python and pandas to do it, but I'm very new to pandas and haven't really used it before. This data is stored in a postgresql database.

Any help would be GREATLY appreciated! Thank you in advance!

Jjman88
  • 67
  • 7

1 Answers1

1

Firstly convert your values of 'Date' column via to_datetime() method:

df['Date']=pd.to_datetime(df['Date']).dt.strftime('%b-%y')

Finally use pivot_table() method:

df=df.pivot_table(index='Name',columns=['Date'],values='Consumption')
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
  • Thank you for the quick response! Unfortunately it's not allowing me to use unstack() method because "the index contains duplicate entries, cannot reshape". – Jjman88 May 24 '21 at 14:31
  • Updated answer...Kindly have a look **:)** – Anurag Dabas May 24 '21 at 16:59
  • 1
    THANK YOU SO MUCH! That's perfect! Now I just have to figure out how to keep this structure, but also include all my other columns I need for my view. – Jjman88 May 24 '21 at 17:30