How To Rename Pandas DataFrame Columns?


How To Rename Pandas DataFrame Columns?

Table Of Contents:

  1. Syntax ‘rename( )’ Method In Pandas.
  2. Examples ‘rename( )’ Method.

(1) Syntax:

DataFrame.rename(mapper=None, *, index=None, columns=None, axis=None, copy=None, inplace=False, level=None, errors='ignore')

Description:

  • Rename the column or Row Labels.

  • Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error.

Parameters:

  • mapper: dict-like or function –
    • Dict-like or function transformations to apply to that axis’ values. Use either mapper and axis to specify the axis to target with mapper, or index and columns.
  • index: dict-like or function –
    • Alternative to specifying axis (mapper, axis=0 is equivalent to index=mapper).
  • columns: dict-like or function –
    • Alternative to specifying axis (mapper, axis=1 is equivalent to columns=mapper).
  • axis: {0 or ‘index’, 1 or ‘columns’}, default 0 –
    • Axis to target with mapper. Can be either the axis name (‘index’, ‘columns’) or number (0, 1). The default is ‘index’.
  • copy: bool, default True –
    • Also copy underlying data.
  • inplace – bool, default False –
    • Whether to modify the DataFrame rather than create a new one. If True then value of copy is ignored.
  • level: int or level name, default None –
    • In the case of a MultiIndex, only rename labels in the specified level.
  • errors: {‘ignore’, ‘raise’}, default ‘ignore’ –
    • If ‘raise’, raise a KeyError when a dict-like mapperindex, 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.

Returns:

  • DataFrame or None – DataFrame with the renamed axis labels or None if inplace=True.

Raises:

  • KeyError – If any of the labels is not found in the selected axis and “errors=’raise’”.

(2) Examples Of rename() Method:

Example-1

df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
df

Output:

# Rename columns using a mapping:

df.rename(columns={"A": "a", "B": "c"})

Output:

# Rename index using a mapping:

df.rename(index={0: "x", 1: "y", 2: "z"})

Output:

# Modifying The Original DataFrame.

df.rename(columns={"A": "aa", "B": "bb"},inplace=True)
df

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *