Как переименовать столбцы в Pandas (с примерами)
Вы можете использовать один из следующих трех методов для переименования столбцов в кадре данных pandas:
Способ 1: переименовать определенные столбцы
df.rename(columns = , inplace = True )
Способ 2: переименовать все столбцы
df.columns = ['new_col1', 'new_col2', 'new_col3', 'new_col4']
Способ 3: заменить определенные символы в столбцах
df.columns = df.columns.str.replace('old_char', 'new_char')
В следующих примерах показано, как использовать каждый из этих методов на практике.
Способ 1: переименовать определенные столбцы
В следующем коде показано, как переименовать определенные столбцы в кадре данных pandas:
import pandas as pd #define DataFrame df = pd.DataFrame() #list column names list(df) ['team', 'points', 'assists', 'rebounds'] #rename specific column names df.rename(columns = , inplace = True ) #view updated list of column names list(df) ['team_name', 'points_scored', 'assists', 'rebounds']
Обратите внимание, что столбцы «команда» и «очки» были переименованы, а имена всех остальных столбцов остались прежними.
Способ 2: переименовать все столбцы
В следующем коде показано, как переименовать все столбцы в кадре данных pandas:
import pandas as pd #define DataFrame df = pd.DataFrame() #list column names list(df) ['team', 'points', 'assists', 'rebounds'] #rename all column names df.columns = ['_team', '_points', '_assists', '_rebounds'] #view updated list of column names list(df) ['_team', '_points', '_assists', '_rebounds']
Обратите внимание, что этот метод быстрее использовать, если вы хотите переименовать большинство или все имена столбцов в DataFrame.
Способ 3: заменить определенные символы в столбцах
В следующем коде показано, как заменить определенный символ в имени каждого столбца:
import pandas as pd #define DataFrame df = pd.DataFrame() #list column names list(df) ['team', 'points', 'assists', 'rebounds'] #rename $ with blank in every column name df.columns = df.columns.str.replace('$', '') #view updated list of column names list(df) ['team', 'points', 'assists', 'rebounds']
Обратите внимание, что этот метод позволил нам быстро удалить «$» из имени каждого столбца.
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:
pandas.DataFrame.rename#
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 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 creating a new one. If True then value of copy is ignored.
level int or level name, default None
In case of a MultiIndex, only rename labels in the specified level.
errors , default ‘ignore’
If ‘raise’, raise a KeyError 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.
Returns DataFrame or None
DataFrame with the renamed axis labels or None if inplace=True .
If any of the labels is not found in the selected axis and “errors=’raise’”.
DataFrame.rename supports two calling conventions
We highly recommend using keyword arguments to clarify your intent.
Rename columns using a mapping:
>>> df = pd.DataFrame("A": [1, 2, 3], "B": [4, 5, 6]>) >>> df.rename(columns="A": "a", "B": "c">) a c 0 1 4 1 2 5 2 3 6
Rename index using a mapping:
>>> df.rename(index=0: "x", 1: "y", 2: "z">) A B x 1 4 y 2 5 z 3 6
Cast index labels to a different type:
>>> df.index RangeIndex(start=0, stop=3, step=1) >>> df.rename(index=str).index Index(['0', '1', '2'], dtype='object')
>>> df.rename(columns="A": "a", "B": "b", "C": "c">, errors="raise") Traceback (most recent call last): KeyError: ['C'] not found in axis
Using axis-style parameters:
>>> df.rename(str.lower, axis='columns') a b 0 1 4 1 2 5 2 3 6
>>> df.rename(1: 2, 2: 4>, axis='index') A B 0 1 4 2 2 5 4 3 6
pandas.DataFrame.rename#
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 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 creating a new one. If True then value of copy is ignored.
level int or level name, default None
In case of a MultiIndex, only rename labels in the specified level.
errors , default ‘ignore’
If ‘raise’, raise a KeyError 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.
Returns : DataFrame or None
DataFrame with the renamed axis labels or None if inplace=True .
If any of the labels is not found in the selected axis and “errors=’raise’”.
DataFrame.rename supports two calling conventions
We highly recommend using keyword arguments to clarify your intent.
Rename columns using a mapping:
>>> df = pd.DataFrame("A": [1, 2, 3], "B": [4, 5, 6]>) >>> df.rename(columns="A": "a", "B": "c">) a c 0 1 4 1 2 5 2 3 6
Rename index using a mapping:
>>> df.rename(index=0: "x", 1: "y", 2: "z">) A B x 1 4 y 2 5 z 3 6
Cast index labels to a different type:
>>> df.index RangeIndex(start=0, stop=3, step=1) >>> df.rename(index=str).index Index(['0', '1', '2'], dtype='object')
>>> df.rename(columns="A": "a", "B": "b", "C": "c">, errors="raise") Traceback (most recent call last): KeyError: ['C'] not found in axis
Using axis-style parameters:
>>> df.rename(str.lower, axis='columns') a b 0 1 4 1 2 5 2 3 6
>>> df.rename(1: 2, 2: 4>, axis='index') A B 0 1 4 2 2 5 4 3 6
pandas.DataFrame.rename#
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 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 creating a new one. If True then value of copy is ignored.
level int or level name, default None
In case of a MultiIndex, only rename labels in the specified level.
errors , default ‘ignore’
If ‘raise’, raise a KeyError 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.
Returns : DataFrame or None
DataFrame with the renamed axis labels or None if inplace=True .
If any of the labels is not found in the selected axis and “errors=’raise’”.
DataFrame.rename supports two calling conventions
We highly recommend using keyword arguments to clarify your intent.
Rename columns using a mapping:
>>> df = pd.DataFrame("A": [1, 2, 3], "B": [4, 5, 6]>) >>> df.rename(columns="A": "a", "B": "c">) a c 0 1 4 1 2 5 2 3 6
Rename index using a mapping:
>>> df.rename(index=0: "x", 1: "y", 2: "z">) A B x 1 4 y 2 5 z 3 6
Cast index labels to a different type:
>>> df.index RangeIndex(start=0, stop=3, step=1) >>> df.rename(index=str).index Index(['0', '1', '2'], dtype='object')
>>> df.rename(columns="A": "a", "B": "b", "C": "c">, errors="raise") Traceback (most recent call last): KeyError: ['C'] not found in axis
Using axis-style parameters:
>>> df.rename(str.lower, axis='columns') a b 0 1 4 1 2 5 2 3 6
>>> df.rename(1: 2, 2: 4>, axis='index') A B 0 1 4 2 2 5 4 3 6