How to iterate over Pandas Data frame and replace multiple rows
1
0
Entering edit mode
24 months ago
Jakpa ▴ 50

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,

DataFrame Python Pandas • 880 views
ADD COMMENT
2
Entering edit mode
24 months ago
Jakpa ▴ 50

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])
ADD COMMENT

Login before adding your answer.

Traffic: 2152 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6