How to iterate over Pandas Data frame and replace multiple rows

Question:

Here is first 5 rows of my Pd dataframe:

0   Stage II
1   Stage III
2   Stage II
3   Stage IV
4   Stage II

It has 428 rows and one column.

I want to replace Stage I, II, III, and IV with Grade I, II, III, and IV respectively so that I will have a pd df like this:

0   Grade II
1   Grade III
2   Grade II
3   Grade IV
4   Grade II

I used replace like this :

target_data.replace("Stage II", "Grade II", inplace =True ). it worked but it seems I have to repeat it 4times for others.i.e, I, III,IV.

I also tried

for row in target_data.iterrows():
    
    if row == "Stage I":
        row.replace("Stage I", "Grade I" )
        if row == "Stage II":
            row.replace("Stage II", "Grade II" )
            if row == "Stage III":
                row.replace("Stage III", "Grade III" )
                if row == "Stage IV":
                    row.replace("Stage IV", "Grade IV" )

it did not yield what I wanted.

Any suggestions to implement it in a more pythonic way?

Asked By: kukulu

||

Answers:

You can try this:

for i in ["Stage I", "Stage II", "Stage III", "Stage IV"]:
    your_df[col_name] = your_df[col_name].str.replace(i, "Grade " + i.split()[-1])
Answered By: padu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.