Изменить порядок столбцов Pandas DataFrame в Python
Опубликовано: 27 Марта, 2022
Давайте посмотрим, как изменить порядок столбцов DatFrame.
Алгоритм:
- Создайте DatFrame.
- Переназначьте тот же DataFrame с измененным порядком столбцов.
- Распечатайте DataFame.
Example 1 :
# importing the modulesimport pandas as pdimport numpy as np # creating the DataFramemy_data = {"Sr.no": [1, 2, 3, 4, 5], "Name": ["Ram", "Sham", "Sonu", "Tinu", "Monu"], "Maths Score": [45, 67, 89, 74, 56]}df = pd.DataFrame(data = my_data) # printing the original DataFrameprint("My Original DataFrame")print(df) # altering the DataFramedf = df[["Sr.no", "Maths Score", "Name"]] # printing the altered DataFrameprint("After altering Name and Maths Score")print(df) |
Output:

Example 2 :
# importing the modulesimport pandas as pd # creating the DataFramel1 =["Amar", "Barsha", "Carlos", "Tanmay", "Misbah"]l2 =["Alpha", "Bravo", "Charlie", "Tango", "Mike"]l3 =[23, 25, 22, 27, 29]l4 =[69, 54, 73, 70, 74]df = pd.DataFrame(list(zip(l1, l2, l3, l4))) df.columns =["Name", "Code", "Age", "Weight"] # printing the original DataFrameprint("My Original DataFrame")print(df) # altering the DataFramedf = df[["Name", "Code", "Weight", "Age"]] # printing the altered DataFrameprint("After altering Weight and Age")print(df) |
Output :

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course