12

in one of the columns in my dataframe I have five values:

1,G,2,3,4

How to make it change the name of all "G" to 1

I tried:

df = df['col_name'].replace({'G': 1})

I also tried:

df = df['col_name'].replace('G',1)

"G" is in fact 1 (I do not know why there is a mixed naming)

Edit:

works correctly with:

df['col_name'] = df['col_name'].replace({'G': 1})
2
  • Won't you have duplicate column names? Do you want that? Commented Jul 23, 2019 at 13:31
  • 5
    df['col_name'].replace({'G': 1}) is the right (a right) thing to do. You just need to assign it back to the dataframe appropriately. df['col_name'] = df['col_name'].replace({'G': 1}) OR df.update(df['col_name'].replace({'G': 1})) OR df = df.assign(col_name=df['col_name'].replace({'G': 1})) Commented Jul 23, 2019 at 13:36

4 Answers 4

18

If I am understanding your question correctly, you are trying to change the values in a column and not the column name itself.

Given you have mixed data type there, I assume that column is of type object and thus the number is read as string.

df['col_name'] = df['col_name'].str.replace('G', '1')
Sign up to request clarification or add additional context in comments.

2 Comments

There is no reason why OP's approach of df['col_name'].replace({'G': 1}) won't work. Nothing magical about df['col_name'].str.replace('G', '1')) is any better. It's the assignment back to the dataframe that is messed up.
I dont think this would solve the issue. I manually checked and df['col_name'].replace({'G': 1}) is working fine too.
4

You could try the following line

df.replace('G', 1, inplace=True)

Comments

1

use numpy

import numpy as np

df['a'] = np.where((df.a =='G'), 1, df.a)

Comments

0

You can try this, lets say your data is like :

ab=pd.DataFrame({'a':[1,2,3,'G',5]})

And you will replace it as :

ab1=ab.replace('G',4)

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.