Rename column values using pandas DataFrame

16,734

Solution 1

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')

Solution 2

You could try the following line

df.replace('G', 1, inplace=True)
Share:
16,734

Related videos on Youtube

tbone
Author by

tbone

Updated on September 17, 2022

Comments

  • tbone
    tbone about 1 year

    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})
    
    • user3483203
      user3483203 over 4 years
      Won't you have duplicate column names? Do you want that?
    • piRSquared
      piRSquared over 4 years
      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}))
  • piRSquared
    piRSquared over 4 years
    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.
  • MNA
    MNA over 4 years
    I dont think this would solve the issue. I manually checked and df['col_name'].replace({'G': 1}) is working fine too.