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)
Related videos on Youtube
Author by
tbone
Updated on September 17, 2022Comments
-
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 over 4 yearsWon't you have duplicate column names? Do you want that?
-
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})
ORdf.update(df['col_name'].replace({'G': 1}))
ORdf = df.assign(col_name=df['col_name'].replace({'G': 1}))
-
-
piRSquared over 4 yearsThere is no reason why OP's approach of
df['col_name'].replace({'G': 1})
won't work. Nothing magical aboutdf['col_name'].str.replace('G', '1'))
is any better. It's the assignment back to the dataframe that is messed up. -
MNA over 4 yearsI dont think this would solve the issue. I manually checked and df['col_name'].replace({'G': 1}) is working fine too.