📜  在Python中更改 Pandas DataFrame 列的顺序

📅  最后修改于: 2022-05-13 01:54:57.084000             🧑  作者: Mango

在Python中更改 Pandas DataFrame 列的顺序

让我们看看如何更改 DataFrame 列的顺序。

算法 :

  • 创建一个数据框。
  • 重新分配相同的 DataFrame 并更改列的顺序。
  • 打印数据帧。

示例 1:

Python3
# importing the modules
import pandas as pd
import numpy as np
 
# creating the DataFrame
my_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 DataFrame
print("My Original DataFrame")
print(df)
 
# altering the DataFrame
df = df[['Sr.no', 'Maths Score', 'Name']]
 
# printing the altered DataFrame
print('After altering Name and Maths Score')
print(df)


Python3
# importing the modules
import pandas as pd
  
# creating the DataFrame
l1 =["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 DataFrame
print("My Original DataFrame")
print(df)
  
# altering the DataFrame
df = df[['Name', 'Code', 'Weight', 'Age']]
  
# printing the altered DataFrame
print('After altering Weight and Age')
print(df)


输出:

示例 2:

Python3

# importing the modules
import pandas as pd
  
# creating the DataFrame
l1 =["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 DataFrame
print("My Original DataFrame")
print(df)
  
# altering the DataFrame
df = df[['Name', 'Code', 'Weight', 'Age']]
  
# printing the altered DataFrame
print('After altering Weight and Age')
print(df)

输出 :