Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
rename() method is used to rename any index, column or row. Renaming of column can also be done by
dataframe.columns = [#list]. But in the above case, there isn’t much freedom. Even if one column has to be changed, full column list has to be passed. Also, the above method is not applicable on index labels.
Syntax: DataFrame.rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None)
mapper, index and columns: Dictionary value, key refers to the old name and value refers to new name. Only one of these parameters can be used at once.
axis: int or string value, 0/’row’ for Rows and 1/’columns’ for Columns.
copy: Copies underlying data if True.
inplace: Makes changes in original Data Frame if True.
level: Used to specify level in case data frame is having multiple level index.
Return Type: Data frame with new names
To download the CSV used in code, click here.
Example #1: Changing Index label
In this example, the name column is set as index column and it’s name is changed later using the rename() method.
As shown in the output image, the name of index labels at first and second positions were changed to NEW NAME & NEW NAME 2.
Example #2: Changing multiple column names
In this example, multiple column names are changed by passing a dictionary. Later the result is compared to the data frame returned by using .columns method. Null values are dropped before comparing since NaN==NaN will return false.
As shown in the output image, the results using both ways were same since all values are True.
- Python | pandas.to_markdown() in Pandas
- Add a Pandas series to another Pandas series
- Python | Pandas Index.insert()
- Python | Pandas DatetimeIndex.inferred_freq
- Python | Pandas PeriodIndex.start_time
- Python | Pandas PeriodIndex.week
- Python | Pandas Timestamp.second
- Python | Pandas Series.asobject
- Python | Pandas str.join() to join string/list elements with passed delimiter
- Python | Pandas DataFrame.reset_index()
- Python | Pandas dataframe.notna()
- Python | Pandas PeriodIndex.weekday
- Python | Pandas Series.dt.floor
- Python | Pandas Index.get_slice_bound()
- Python | Pandas Dataframe.duplicated()
- Python | Pandas dataframe.notnull()
- Python | Pandas series.cumprod() to find Cumulative product of a Series
- Use Pandas to Calculate Statistics in Python
- Python | Pandas Timestamp.date
- Python | Pandas Timestamp.ctime
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.