hello! I am trying to add a new column in my pandas Dataframe based off of conditional formatting of an index other than the adjacent cell. I am trying to replicate the "consecutive match" column shown in my image. the excel conditional formula I used to create this column is shown as well! thank so much!
Asked
Active
Viewed 32 times
0
-
1Please do not include images of data. Always put your data in text format, so it can be copy/pasted, or better still post python code that creates your dataframe. This way people will actually be able to use the data to try and reproduce your problem. – joao May 20 '21 at 21:26
-
1Please take the time to read [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) and [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/15239951) – Corralien May 20 '21 at 21:55
1 Answers
1
sr = df["muni_name"]
df["consecutive_match"] = sr.groupby(sr.ne(sr.shift()).cumsum()).cumcount() + 1
>>> df
muni_name consecutive_match
0 East Escambia 1
1 Brewton 1
2 East Escambia 1
3 East Escambia 2
4 East Escambia 3
5 East Escambia 4
6 Atmore 1
7 Brewton 1
8 McCullough-Huxford 1
9 Atmore 1
10 Flomaton 1
11 Flomaton 2
12 Flomaton 3

Corralien
- 109,409
- 8
- 28
- 52