Home > OS >  How to group by a column with Pandas in Python
How to group by a column with Pandas in Python

Time:11-02

Thank you for your feedback in advance! I am working on time series data, which has 2 columns index converted to DateTime object. What I am dealing with looks like below:

enter image description here

I'm trying to parse out sales record by each store so that I can customize sales forecasting for each store. Any recommendations?

Thank you so much!

CodePudding user response:

df = name of dataframe

To get the sale value of a particular store:

df["Sale"].loc[(df["Store"] == "StoreName")]

CodePudding user response:

You can either just query/slice the dataframe by the 'Store' column, or do a .groupby('Store')., or set the index to be ['Store', 'Fiscal_Date']. It's not really clear what you want to do. Perhaps this help?

import pandas as pd

df = pd.DataFrame({'Fiscal_Date':['2013-12-01','2013-12-01','2013-12-02','2013-12-02'],
                    'Store':['A','B','A','B'],
                    'Sale':[12,143,23,21]})


df = df.set_index(['Fiscal_Date']).sort_index()


for store in list(df['Store'].unique()):
    filter_df = df[df['Store'] == store]
    print(filter_df)

Output:

            Store  Sale
Fiscal_Date            
2013-12-01      A    12
2013-12-02      A    23
            Store  Sale
Fiscal_Date            
2013-12-01      B   143
2013-12-02      B    21
  • Related