1

i have a dataframe:

A B C
1 1 1
2 2 2
3 3 3

Now i want to replace 1 with 3, 2 with 7 ,and 3 with 10.

I write the code:

df['A'].replace(3, 10, inplace = True)
df['A'].replace(1, 3, inplace = True)
df['A'].replace(2, 7, inplace = True)

Works fine for me. I do have to replace 3 with 10 first , because if we change the 1 with 3 first, then the transformed 3 will again changed and finally replaced with 10.

Though i have to replace the same formattion for several columns, how come i use function?

I tried to write one but i failed, any guidance?

1 Answer 1

1

If you want to apply this to all columns, you can use

to_replace = {3:10, 1:3, 2:7}

df = df.replace(to_replace)

which outputs

    A   B   C
0   3   3   3
1   7   7   7
2   10  10  10

If you want to replace multiple, but not all, you could try

df = df.replace({'A' : to_replace, 'B': to_replace})

which would outputs.

    A   B   C
0   3   3   1
1   7   7   2
2   10  10  3

If you have many columns you would like to replace you could use

cols = ['A', 'B']

# Then either
df = df.replace({col : to_replace for col in cols})

# or
df[cols] = df[cols].apply(lambda x: x.replace(to_replace))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.