Переименовать определенные столбцы в Pandas

Опубликовано: 27 Марта, 2022

Учитывая pandasDataframe, давайте посмотрим, как переименовать определенные имена столбцов с помощью различных методов.

First, let’s create a Dataframe:

Python3

# import pandas package
import pandas as pd
  
# defining a dictionary
d = {"Name": ["John", "Mary", "Helen"],
     "Marks": [95, 75, 99],
     "Roll No": [12, 21, 9]}
  
# creating the pandas data frame
df = pd.DataFrame(d)
  
df

Выход:

Метод 1. Использование Dataframe.rename ().

Этот метод позволяет переименовать необходимые столбцы в Pandas. Это позволяет нам указать имена столбцов, которые нужно изменить, в виде словаря с ключами и значениями в качестве текущего и нового имен соответствующих столбцов.

Example 1: Renaming a single column.

Python3

# import pandas package
import pandas as pd
  
# defining a dictionary
d = {"Name": ["John", "Mary", "Helen"],
     "Marks": [95, 75, 99],
     "Roll No": [12, 21, 9]}
  
# creating the pandas data frame
df = pd.DataFrame(d)
  
# displaying the columns 
# before renaming
print(df.columns)
  
# renaming the column "A"
df.rename(columns = {"Name": "Names"}, 
          inplace = True)
  
# displaying the columns after renaming
print(df.columns)

Выход:

Example 2: Renaming multiple columns.

Python3



# import pandas package
import pandas as pd
  
# defining a dictionary
d = {"Name": ["John", "Mary", "Helen"],
     "Marks": [95, 75, 99],
     "Roll No": [12, 21, 9]}
  
# creating the pandas dataframe
df = pd.DataFrame(d)
  
# displaying the columns before renaming
print(df.columns)
  
# renaming the columns
df.rename({"Name": "Student Name"
           "Marks": "Marks Obtained"
           "Roll No": "Roll Number"}, 
          axis = "columns", inplace = True)
  
# displaying the columns after renaming
print(df.columns)

Выход:

Example 3: Passing the lambda function to rename columns.

Python3

# using the same modified dataframe
# df from Renaming Multiple Columns
# this adds ":" at the end 
# of each column name
df = df.rename(columns = lambda x: x+":")
  
# printing the columns
print(df.columns)

Выход:

Лямбда- функция - это небольшая анонимная функция, которая может принимать любое количество аргументов, но может иметь только одно выражение. Мы можем использовать его, если нам нужно изменить сразу все столбцы. Это полезно, если количество столбцов велико, и переименовать их с помощью списка или словаря непростая задача (много кода, уф!). В приведенном выше примере мы использовали лямбда-функцию, чтобы добавить двоеточие (':') в конце каждого имени столбца.

Метод 2: Использование атрибута values .

We can use values attribute on the column we want to rename and directly change it.

Python3

# using the same modified dataframe 
# df from Renaming Multiple Columns
# Renaming the third column
df.columns.values[2] = "Roll Number" 
  
# printing the columns
print(df.columns)

Выход:

Метод 3: Использование нового списка имен столбцов.

We pass the updated column names as a list to rename the columns. The length of the list we provide should be the same as the number of columns in the data frame. Otherwise, an error occurs.

Python3

# Creating a list of new columns
df_cols = ["Student Name"
           "Marks Obtained",
           "Roll Number"]
  
# printing the columns 
# before renaming
print(df.columns)
  
# Renaming the columns
df.columns = df_cols
  
# printing the columns 
# after renaming
print(df.columns)

Выход:

Метод 4: Использование Dataframe.columns.str.replace () .

In general, if the number of columns in the Pandas dataframe is huge, say nearly 100, and we want to replace the space in all the column names (if it exists) by an underscore. It is not easy to provide a list or dictionary to rename all the columns. Therefore, we use a method as below –

Python3

# printing the column 
# names before renaming
print(df.columns)
  
# Replacing the space in column 
# names by an underscore
df.columns = df.columns.str.replace(" ", "_")
  
# printing the column names 
# after renaming
print(df.columns)

Выход:

Кроме того, можно использовать другие строковые методы, такие как str.lower , чтобы сделать все имена столбцов строчными.

Примечание: Предположим, что имя столбца отсутствует в исходном фрейме данных, но есть в словаре, предоставленном для переименования столбцов. По умолчанию параметр errors функции rename () имеет значение ignore. Таким образом, ошибка не отображается, а существующие столбцы переименовываются в соответствии с инструкциями. Напротив, если мы устанавливаем для параметра ошибок значение «raise», возникает ошибка, указывающая, что конкретный столбец не существует в исходном фрейме данных.

Ниже приведен пример того же:

Example 1: No error is raised as by default errors is set to ‘ignore.’

Python3

# NO ERROR IS RAISED 
  
# import pandas package
import pandas as pd
  
# defining a dictionary
d = {"A": [1, 2, 3], 
     "B": [4, 5, 6]}
  
# creating the pandas dataframe
df = pd.DataFrame(d)
  
# displaying the columns before renaming
print(df.columns)
  
# renaming the columns
# column "C" is not in 
# the original dataframe 
# errors parameter is
# set to "ignore" by default
df.rename(columns = {"A": "a", "B": "b",
                     "C": "c"}, 
          inplace = True)
  
# displaying the columns
# after renaming
print(df.columns)

Выход:

Example 2: Setting the parameter errors to ‘raise.’ Error is raised ( column C does not exist in the original data frame.)

Python3

# ERROR IS RAISED 
  
# import pandas package
import pandas as pd
  
# defining a dictionary
d = {"A": [1, 2, 3],
     "B": [4, 5, 6]}
  
# creating the pandas dataframe
df = pd.DataFrame(d)
  
# displaying the columns
# before renaming
print(df.columns)
  
# renaming the columns
# column "C" is not in the 
# original dataframe setting
# the errors parameter to "raise"
df.rename(columns = {"A": "a", "B": "b"
                     "C": "c"}, 
          inplace = True, errors = "raise")
  
# displaying the columns 
# after renaming
print(df.columns)

Выход:

Возникла ошибка

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.