rename elements in a column of a data frame using pandas
Asked Answered
S

3

17

Using pandas:

df = pd.DataFrame({'n':['d','a','b','c','c','a','d','b'], 'v':[1,2,1,2,2,1,1,1]})

How can I rename the elements in df.n, such that a changes to x, b to y, c to w and d to z, resulting in:

   n  v
0  z  1
1  x  2
2  y  1
3  w  2
  ...
Susan answered 31/8, 2013 at 13:26 Comment(0)
S
56

You can pass a dictionary of replacement values into the Series replace method:

In [11]: df['n'].replace({'a': 'x', 'b': 'y', 'c': 'w', 'd': 'z'})
Out[11]: 
0    z
1    x
2    y
3    w
4    w
5    x
6    z
7    y
Name: n, dtype: object

In [12]: df['n'] = df['n'].replace({'a': 'x', 'b': 'y', 'c': 'w', 'd': 'z'})
Sanitize answered 31/8, 2013 at 14:2 Comment(1)
Hello, how can I do exactly this but creating a df column instead of a list?Germainegerman
T
2

You can also use the below one:

df['n'].replace(['a', 'b', 'c', 'd'], ['x', 'y', 'w', 'z'])

This will replace all the a with x, b with y, c with w, and d with z. Note: if you pass two lists they both must be the same length.

Tericaterina answered 2/9, 2021 at 3:20 Comment(0)
W
0

Slightly Modified from above:

movies['price'].replace({"$":"low","$$":"moderate","$$$":"high","$$$$":"very high"},inplace=True)

"Use inplace =True " otherwise dataframe won't be updated.

Wee answered 30/6, 2022 at 18:37 Comment(1)
This solution does not answer the question. In addition, @Andy Hayden's answer also provides an update of the DataFrame.Swabber

© 2022 - 2024 — McMap. All rights reserved.