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
JavaScript
x
2
1
df.loc[df["state"] == "no", "comment"] = ""
2
but I dont know how take the row number into account.
Input:
JavaScript
1
7
1
state value comment
2
0 yes 6 example1
3
1 no 34 example2
4
2 no 25 example3
5
3 yes 123 example4
6
4 no 55 example5
7
Output:
JavaScript
1
7
1
state value comment
2
0 yes 6 example1
3
1 no =F2 example2
4
2 no =F3 example3
5
3 yes 123 example4
6
4 no =F5 example5
7
Advertisement
Answer
Use boolean indexing:
JavaScript
1
4
1
m = df['state'].eq('no')
2
3
df.loc[m, 'value'] = '=F'+(df.index[m]+1).astype(str)
4
Output:
JavaScript
1
7
1
state value comment
2
0 yes 6 example1
3
1 no =F2 example2
4
2 no =F3 example3
5
3 yes 123 example4
6
4 no =F5 example5
7