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
...
We can use pandas DataFrame rename() function to rename columns and indexes.
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', ...])
Pandas rename() method is used to rename any index, column or row. Renaming of column can also be done by dataframe. columns = [#list] .
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.
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'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With