Python : How to reset index if a row matches a condition?

Viewed 55

My dataframe contains a column where value 'aa' repeats after every 3rd index. I want to reset my index to 0 wherever it finds 'aa'.

Current Dataframe:

name loc
0 john aa
1 popp bb
2 lily cc
3 fete aa
4 bruh gg
5 kiku uu
6 kiku aa
7 kiku ur

Expected output:

name loc
0 john aa
1 popp bb
2 lily cc
0 fete aa
1 bruh gg
2 kiku uu
0 kiku aa
1 kiku ur

and so on..... I have tried below but it is not giving me the results.

if ('aa' in df['loc'].values):
   df = df.reset_index(drop=True)

Really looking for some guidance as I am new to Python and unable to figure out the solution.

1 Answers

This may help you

import io
import pandas as pd

data = """name,loc
john,aa
popp,bb
lily,cc
fete,aa
bruh,gg
kiku,uu
kiku,aa
kiku,ur
"""

data = io.StringIO(data)
df = pd.read_csv(data)

print(df)

   name loc
0  john  aa
1  popp  bb
2  lily  cc
3  fete  aa
4  bruh  gg
5  kiku  uu
6  kiku  aa
7  kiku  ur

df.index = df.index.where(df['loc'] != 'aa', 0)

lst = df.index.to_list()
ac = -1
for i, v in enumerate(lst[:]):
    if v == 0:
        ac = 0
        continue
    if i == 0 or ac < 0:
        continue
    ac += 1
    lst[i] = ac

df.index = lst

print(df)

   name loc
0  john  aa
1  popp  bb
2  lily  cc
0  fete  aa
1  bruh  gg
2  kiku  uu
0  kiku  aa
1  kiku  ur

 
Related