Rename Columns in a Pandas Dataframe
Renaming Columns using the `rename` Function
One way of renaming the columns in a Pandas Dataframe is by using the `rename` function. This method is quite useful when we need to rename specific columns with new names. The `rename` function takes the following parameters:
- mapper: A dictionary or a function that maps the old column names to the new column names.
- index: A boolean value that indicates whether the index should be renamed or not. The default value is `False`.
- columns: A boolean value that indicates whether the columns should be renamed or not. The default value is `True`.
- axis: The axis along which the renaming should be done. The default value is `0` (index).
- copy: A boolean value that indicates whether a copy of the DataFrame should be returned or not. The default value is `False`.
- inplace: A boolean value that indicates whether the renaming should be done inplace or not. The default value is `False`.
- level: The level of the MultiIndex to rename. The default value is `None`.
Renaming Columns Using the `dfrename` Function
Use the `dfrename` function and refer the columns to be renamed. Not all the columns have to be renamed. For example, to rename the `age` column to `age_group`, use the following code:
```python import pandas as pd df = pd.DataFrame({'name': ['John', 'Mary', 'Peter'], 'age': [20, 25, 30]}) df = dfrename(df, {'age': 'age_group'}) print(df) ```Renaming Columns Inplace
You can use one of the following three methods to rename columns in a pandas DataFrame inplace:
- Using the `rename` function with the `inplace` parameter set to `True`: ```python df.rename(columns={'age': 'age_group'}, inplace=True) ```
- Using the `dfrename` function with the `inplace` parameter set to `True`: ```python dfrename(df, {'age': 'age_group'}, inplace=True) ```
- Using the `assign` function to create a new DataFrame with the renamed columns: ```python df = df.assign(age_group=df['age']) ```
Comments