Как преобразовать индекс в столбец в фрейме данных Pandas?

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

Pandas - это мощный инструмент, который используется для анализа данных и построен на основе библиотеки Python. Библиотека Pandas позволяет пользователям эффективно и действенно создавать фреймы данных (таблицы данных) и временные ряды и управлять ими. Эти фреймы данных можно использовать для обучения и тестирования моделей машинного обучения и анализа данных.

Преобразование индекса в столбцы

By default, each row of the dataframe has an index value. The rows in the dataframe are assigned index values from 0 to the (number of rows – 1) in a sequentially order with each row having one index value. There are many ways to convert an index to a column in a pandas dataframe. Let’s create a dataframe.

Python3

# importing the pandas library as pd
import pandas as pd
  
  
# Creating the dataframe df
df = pd.DataFrame({"Roll Number": ["20CSE29", "20CSE49", "20CSE36", "20CSE44"],
                   "Name": ["Amelia", "Sam", "Dean", "Jessica"],
                   "Marks In Percentage": [97, 90, 70, 82],
                   "Grade": ["A", "A", "C", "B"],
                   "Subject": ["Physics", "Physics", "Physics", "Physics"]})
  
# Printing the dataframe
df

Выход:

Method 1: The simplest method is to create a new column and pass the indexes of each row into that column by using the Dataframe.index function.

Python3

import pandas as pd
  
  
df = pd.DataFrame({"Roll Number": ["20CSE29", "20CSE49", "20CSE36", "20CSE44"],
                   "Name": ["Amelia", "Sam", "Dean", "Jessica"],
                   "Marks In Percentage": [97, 90, 70, 82],
                   "Grade": ["A", "A", "C", "B"],
                   "Subject": ["Physics", "Physics", "Physics", "Physics"]})
  
# Printing the dataframe
df["index"] = df.index
df

Выход:

Method 2: We can also use the Dataframe.reset_index function to convert the index as a column. The inplace parameter reflects the change in the dataframe to stay permanent.

Python3

import pandas as pd
  
  
df = pd.DataFrame({"Roll Number": ["20CSE29", "20CSE49", "20CSE36", "20CSE44"],
                   "Name": ["Amelia", "Sam", "Dean", "Jessica"],
                   "Marks In Percentage": [97, 90, 70, 82],
                   "Grade": ["A", "A", "C", "B"],
                   "Subject": ["Physics", "Physics", "Physics", "Physics"]})
  
# Printing the dataframe
df.reset_index(level=0, inplace=True)
df

Выход:

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

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