Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rename elements in a column of a data frame using pandas

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
  ...
like image 887
HappyPy Avatar asked Aug 31 '13 13:08

HappyPy


People also ask

How do I rename a value in a column in pandas?

We can use pandas DataFrame rename() function to rename columns and indexes.

How do you rename values in a data frame?

Suppose that you want to replace multiple values with multiple new values for an individual DataFrame column. In that case, you may use this template: df['column name'] = df['column name']. replace(['1st old value', '2nd old value', ...], ['1st new value', '2nd new value', ...])

How do I rename data in a DataFrame in Python?

Pandas rename() method is used to rename any index, column or row. Renaming of column can also be done by dataframe. columns = [#list] .

How do I add a name to a column in pandas?

Adding column name to the DataFrame : We can add columns to an existing DataFrame using its columns attribute. Output : Now the DataFrame has column names. Renaming column name of a DataFrame : We can rename the columns of a DataFrame by using the rename() function.


1 Answers

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'})
like image 73
Andy Hayden Avatar answered Oct 15 '22 04:10

Andy Hayden