shamalaia
shamalaia

Reputation: 2361

pandas GroupBy plotting each group

I have some data from which I want to extract a time series of revenues (sum of Dollars in different dates Day over different locations Where) for different products (x and y).

import pandas as pd

#Create data
data = {'Day': [1,1,2,2,3,3],
        'Where': ['A','B','A','B','B','B'],
        'What': ['x','y','x','x','x','y'],
        'Dollars': [100,200,100,100,100,200]}

index = range(len(data['Day']))

columns = ['Day','Where','What','Dollars']


df = pd.DataFrame(data,  index=index, columns=columns)
df

ddd

To do so, I group data by Day and What and sum over Dollars:

#Group by Day and What and sum Dollars (for each Where)
print(df.groupby(['Day', 'What'])['Dollars'].sum())

ccc

Now, I would like to make a time series for x and y like so:

iii

I tried the following, but it is clearly not working:

items = df.What.unique()

ax = plt.figure()
for item in items:
    df_tmp = df[['Day']][df.What == item]
    plt.plot(df_tmp['Day'],df_tmp,'.-',label=item)

fff

Can someone, please, put me in the right direction? Is there a faster way to get to the right result?

Upvotes: 5

Views: 6146

Answers (1)

cs95
cs95

Reputation: 403208

IIUC, unstack, and plot:

(df.groupby(['Day', 'What'])['Dollars']
   .sum()
   .unstack('What', fill_value=0)
   .plot())
plt.show()

enter image description here

Upvotes: 6

Related Questions