How to iterate over Pandas Data frame and replace multiple rows
Hello everyone,
This is first 5 rows of my Pandas df:
target_data.head()
0 Stage II
1 Stage III
2 Stage II
3 Stage IV
4 Stage II
The df has 428 rows and its just one column. The rows have Stage I, II, III, and IV.
I want to replace Stage I, II, III and IV with Grade I, II; III, and IV respectively.
I used the replace Method like this :
target_data.replace("Stage II",
"Grade II",
inplace =True )
Which actually did the replacement. However, with this, I have to write the line of code 4times which seems not to be ok by me.
I try using :
for index, row in target_data.iterrows():
row.replace("Stage II", "Grade II" )
row.replace("Stage I", "Grade I" )
row.replace("Stage III", "Grade III" )
row.replace("Stage IV", "Grade IV" )
But, It did not yield what I want. I know that there is something am not doing properly.
How do I iterate over my df using the iterrows to achieve what I want? or any other method to obtain my desired result will be appreciated.
Regards,
• 1,643 views
•
link
1 answer
solved!
for i in ["Stage I", "Stage II", "Stage III", "Stage IV"]:
target_data["BlcaGrade"] = target_data["BlcaGrade"].str.replace(i, "Grade " + i.split()[-1])
• 0 views
•
link
Log in to answer this question.