Home > front end >  Sum 1 column based from date selection in Pandas
Sum 1 column based from date selection in Pandas

Time:05-22

I am trying to figure out a way to do this sum in one line, or without having to create another dataframe in memory.

I have a DF with 3 columns. ['DateCreated', 'InvoiceNumber', 'InvoiceAmount']

I am trying to SUM the invoice amount during certain date ranges.

I have this working, but I want to do it without having to create a DF then sum the column. Any help is appreciated.

        yesterday_sales_df = df[(df['DateCreated'] > yesterday_date) & (df['DateCreated'] < tomorrow_date)]
        yesterday_sales_total = yesterday_sales_df['InvoiceAmount'].sum()
        print(yesterday_sales_total)

Thanks

CodePudding user response:

You can try with loc

yesterday_sales_total = df.loc[(df['DateCreated'] > yesterday_date) & (df['DateCreated'] < tomorrow_date), 'InvoiceAmount'].sum()

CodePudding user response:

You can use this as well

# filter df with query
yesterday_sales_total = df.query("(DateCreated > @yesterday_date) & (DateCreated < @tomorrow_date)")['InvoiceAmount'].sum()
  • Related