I have a table like the following, and I want to fill a new column based on conditions from other columns. In this case:
- Having the same value in Cond1
- Amount being different than zero
- Being from previous months
Column "CountPreviousMonth" is what I need to fill out
| Cond1 | Amount | Month | CountPreviousMonth |
|---|---|---|---|
| a | 10 | 1 | 0 |
| a | 20 | 2 | 1 |
| a | 15 | 3 | 2 |
| b | 10 | 1 | 0 |
| b | 0 | 2 | 1 |
| b | 15 | 3 | 1 |
| c | 5 | 1 | 0 |
| c | 25 | 2 | 1 |
| c | 15 | 3 | 2 |
When month is 1 then the count is zero because is the first one. In Cond1=b it stays at count = 1 because in Month 2 the Amount was zero
In Excel I used COUNTIFS but would like to do it in Python, where I could do it in a for loop but the real table has many rows and it wouldn't be efficient. Is there a better way to calculate it?