Python dataframe rename one column

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 (с примерами)

Вы можете использовать один из следующих трех методов для переименования столбцов в кадре данных 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 

Источник

How to Rename a Column in Pandas – Python Pandas Dataframe Renaming Tutorial

Ihechikara Vincent Abba

Ihechikara Vincent Abba

A Pandas Dataframe is a 2-dimensional data structure that displays data in tables with rows and columns.

In this article, you’ll learn how to rename columns in a Pandas Dataframe by using:

How to Rename a Column in Pandas Using the rename() Function

In this section, you’ll see a practical example of renaming a Pandas Dataframe using the rename() function.

Let’s begin by passing data into a Dataframe object:

import pandas as pd students = < "firstname": ["John", "Jane", "Jade"], "lastname": ["Doe", "Done", "Do"] ># convert student names into a Dataframe df = pd.DataFrame(students) print(df)
# Output firstname lastname 0 John Doe 1 Jane Done 2 Jade Do

In the example above, we created a Python dictionary which we used to store the firstname and lastname of students.

We then converted the dictionary to a Dataframe by passing it as a parameter to the Pandas Dataframe object: pd.DataFrame(students) .

When printed to the console, we had this table printed out:

 firstname lastname 0 John Doe 1 Jane Done 2 Jade Do

The goal here is to rename the columns. We can do that using the rename() function.

Here’s what the syntax looks like:

Let’s go ahead and change the column names ( firstname and lastname ) in the table from lowercase to uppercase ( FIRSTNAME and LASTNAME ).

import pandas as pd students = < "firstname": ["John", "Jane", "Jade"], "lastname": ["Doe", "Done", "Do"] ># convert student names into a Dataframe df = pd.DataFrame(students) df.rename(columns=, inplace=True) print(df)
# Output FIRSTNAME LASTNAME 0 John Doe 1 Jane Done 2 Jade Do

In the code above, we specified that the columns firstname and lastname should be renamed to FIRSTNAME and LASTNAME , respectively: df.rename(columns=, inplace=True)

You’ll notice that we added the inplace=True parameter. This helps in persisting the new changes in the Dataframe. Delete the parameter and see what happens 😉

You can rename the columns to whatever you want. For instance, we can use SURNAME instead of lastname by doing this:

import pandas as pd students = < "firstname": ["John", "Jane", "Jade"], "lastname": ["Doe", "Done", "Do"] ># convert student names into a Dataframe df = pd.DataFrame(students) df.rename(columns=, inplace=True) print(df)
# Output FIRSTNAME SURNAME 0 John Doe 1 Jane Done 2 Jade Do

You can change just one column name, too. You are not required to change all the column names at the same time.

How to Rename a Column in Pandas Using a List

You can access the column names of a Dataframe using df.columns . Consider the table below:

 firstname lastname 0 John Doe 1 Jane Done 2 Jade Do

We can print out the column names with the code below:

print(df.columns) # Index(['firstname', 'lastname'], dtype='object')

Using that, we can rename the column of a Dataframe. Here’s an example:

import pandas as pd students = < "firstname": ["John", "Jane", "Jade"], "lastname": ["Doe", "Done", "Do"] ># convert student names into a Dataframe df = pd.DataFrame(students) df.columns = ["FIRSTNAME", "SURNAME"] print(df)
# Output FIRSTNAME SURNAME 0 John Doe 1 Jane Done 2 Jade Do

In the example above, we put the new column names in a List and assigned it to the Dataframe columns: df.columns = [«FIRSTNAME», «SURNAME»] .

This will override the previous column names.

How to Rename a Column in Pandas Using the set_axis() Function

The syntax for renaming a column with the set_axis() function looks like this:

df.set_axis([NEW_COLUMN_NAME. ], axis="columns")
import pandas as pd students = < "firstname": ["John", "Jane", "Jade"], "lastname": ["Doe", "Done", "Do"] ># convert student names into a Dataframe df = pd.DataFrame(students) df.set_axis(["FIRSTNAME", "SURNAME"], axis="columns", inplace=True) print(df)
# Output FIRSTNAME SURNAME 0 John Doe 1 Jane Done 2 Jade Do

Note that the inplace=True parameter might raise a warning because it’s deprecated for the set_axis() function and will be replaced in the future.

Summary

In this article, we talked about renaming a column in Pandas.

We saw different methods that can be used to rename a Pandas Dataframe column with code examples.

Источник

Читайте также:  Use sprite image in css
Оцените статью