Skip to content
Advertisement

How to calculate with conditions in pandas?

I have a dataframe like this, I want to calculate and add a new column which follows the formula: Value = A(where Time=1) + A(where Time=3), I don’t want to use A (where Time=5).

JavaScript

I know how to do by selecting the cell needed for the formula, but is there any other better ways to perform the calculation? I suspect I need to add a condition but not sure how, any suggestion?

Advertisement

Answer

Use Series.eq with DataFrame.groupby and Series.cumsum to create groups and add.

JavaScript

or if you want to identify it based on the non-equivalence with 5:

JavaScript

Output

JavaScript

MISSING VALUES

JavaScript

Output

JavaScript

or filling all except where Time is 5

JavaScript

Why not use apply here?

Even in a small data frame it is already slower

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement