How can I reach the 'Counter' column with pandas: If status A -> count up by one. if status B or C -> reduce by one.
| Index | Status | Counter |
|---|---|---|
| 1 | A | 1 |
| 2 | A | 2 |
| 3 | A | 3 |
| 4 | B | 2 |
| 5 | C | 1 |
| 6 | A | 2 |
| 7 | B | 1 |
| 8 | A | 2 |
| 9 | A | 3 |
| 10 | B | 2 |
CodePudding user response:
Map the values to 1/-1 with numpy.where, then perform a cumsum:
import numpy as np
df['Counter'] = (np.where(df['Status'].eq('A'), 1, -1)
.cumsum()
)
Output:
Index Status Counter
0 1 A 1
1 2 A 2
2 3 A 3
3 4 B 2
4 5 C 1
5 6 A 2
6 7 B 1
7 8 A 2
8 9 A 3
9 10 B 2
CodePudding user response:
I think what you need is a loop over the dataframe's rows. You can achieve this by using iterrows on the dataframe:
count = 0
CounterList = []
for i, row in df.iterrows():
if row["Status"] == "A":
count = 1
elif row["Status"] == "B" or row["Status"] == "C":
count -= 1
CounterList.append(count)
df["Counter"] = CounterList
df
Output
| Index | Status | Counter | |
|---|---|---|---|
| 0 | 1 | A | 1 |
| 1 | 2 | A | 2 |
| 2 | 3 | A | 3 |
| 3 | 4 | B | 2 |
| 4 | 5 | C | 1 |
| 5 | 6 | A | 2 |
| 6 | 7 | B | 1 |
| 7 | 8 | A | 2 |
| 8 | 9 | A | 3 |
| 9 | 10 | B | 2 |
CodePudding user response:
Use:
df = pd.DataFrame({'status':['A', 'A', 'B', 'A']})
temp = df['status']=='A'
df['counter'] = temp.replace(False, -1).astype(int).cumsum()
Input:
Output:


