EN VI

Python - Sum a column values before a certain date?

2024-03-10 00:00:06
How to Python - Sum a column values before a certain date

I have Dataframe with multiple columns. The two coloumns I'm looking at are something like this:

           date                score     
 0          ..                   ..
 1          ..                   ..
 2          ..                   ..
 ..         ..                   ..
190      2019-01-14              1
191      2019-01-22              1
192      2019-02-25              0
..         ..                    ..
..         ..                    ..
200      2020-02-19              1  
..         ..                    ..
205      2020-03-15              1
..         ..                    ..
..         ..                    ..
..         ..                    ..

I want a line of code which sums up the values in the score column before the date 2020-02-19.(Beginning of the Corona)

I don't know how to make a conditional term within a syntax to do this. I used groupby and I know it's not the correct way since there is nothing to be grouped.

I want an float variable output with one line of code using pandas not numpy to show the summation of the score column before the date I mentioned.

Solution:

here is one line of code using Pandas to add up the values ​​in the "score" column before the date 2020-02-19:

total_score_before_corona = df[df['date'] < '2020-02-19']['score'].sum()
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login