Skip to content
Advertisement

Replacing values in a pandas dataframe taking row number into account

I have this dataframe taken from an excel file and I want to replace the value column with a string that contains the row number (+1 and with an F so it reference another cell in excel) if the state is “no”. I had no problem replacing some values in the comment column with

df.loc[df["state"] == "no", "comment"] = ""

but I dont know how take the row number into account.

Input:

         state  value  comment
0         yes     6    example1
1          no    34    example2    
2          no    25    example3
3         yes   123    example4
4          no    55    example5

Output:

         state  value  comment
0         yes     6    example1
1          no   =F2    example2    
2          no   =F3    example3
3         yes   123    example4
4          no   =F5    example5

Advertisement

Answer

Use boolean indexing:

m = df['state'].eq('no')

df.loc[m, 'value'] = '=F'+(df.index[m]+1).astype(str)

Output:

  state value   comment
0   yes     6  example1
1    no   =F2  example2
2    no   =F3  example3
3   yes   123  example4
4    no   =F5  example5
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement