Pandas Rename Column and Index With Examples

Sometimes we want to rename columns and indexes in the Pandas DataFrame object. We can use pandas DataFrame rename() function to rename columns and indexes. It supports the following parameters.

  • mapper: dictionary or a function to apply on the columns and indexes. The ‘axis’ parameter determines the target axis – columns or indexes.
  • index: must be a dictionary or function to change the index names.
  • columns: must be a dictionary or function to change the column names.
  • axis: can be int or string. It’s used with ‘mapper’ parameter to define the target axis. The allowed values are (‘index’, ‘columns’) or number (0, 1). The default value is ‘index’.
  • inplace: if True, the DataFrame is changed. Otherwise, a new DataFrame is returned and the current DataFrame remains unchanged. The default value is ‘False’.
  • level: can be int or level name. It’s used in case of a MultiIndex, only rename labels in the specified level.
  • errors: possible values are (‘ignore’, ‘raise’), default is ‘ignore’. If specified as ‘raise’ then KeyError is raised when a dict-like ‘mapper’, ‘index’, or ‘columns’ contains labels that are not present in the Index being transformed. If ‘ignore’, existing keys will be renamed and extra keys will be ignored.

Some important points about rename() function.

  1. It’s recommended to use keyword arguments to clearly specify the intent.
  2. We can rename single column or multiple columns with this function, depending on the values in the dictionary.

Let’s look into some examples of using Pandas rename() function.

1. Pandas Rename Columns

Output:

The above rename() function call can also be written in the following way.

It’s clear that using the keyword arguments is clearer than using the mapper and axis arguments.

2. Pandas Rename Single Column

If you want to rename a single column, just pass the single key-value pair in the columns dict parameter.

Output:

The result will be the same if there is a non-matching mapping in the columns dictionary.

3. Pandas Rename Indexes

If you want to rename indexes, pass the dict for ‘index’ parameter.

Output:

We can also rename indexes using mapper and axis arguments.

4. Pandas Rename Single Index

Output:

5. Changing the DataFrame inplace

If you want to change the source DataFrame itself, pass the inplace argument as True.

Output:

6. Using mapper function to rename columns

Output:

7. Using functions to rename columns and indexes

Output:

8. Strict Rename and Raising KeyError

Output:

9. References

By admin

Leave a Reply

%d bloggers like this: