Murphy McCallum
Murphy McCallum

Reputation: 3

adding a new conditional column in pandas based off different indexes

enter image description here

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!

Upvotes: 0

Views: 36

Answers (1)

Corralien
Corralien

Reputation: 120479

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

Upvotes: 1

Related Questions