在Python中改变Pandas DataFrame列的顺序
在这篇文章中,我们将看到如何在Python中改变数据框列的顺序。
在Python中改变Pandas DataFrame列的顺序的不同方法:
- 使用iloc方法
- 使用loc方法
- 通过传递一个列表来使用一个列的子集
- 使用逆向方法
方法1:使用iloc方法
这里我们使用iloc方法,我们将在iloc中传递不同的索引来改变数据框列的顺序。
# 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")
display(df)
# printing the new DataFrame
print("My new DataFrame")
df.iloc[:,[0,2,1]]
Python
输出:
方法2:使用loc方法
在这里,我们将把列名与loc一起传递。
# 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")
display(df)
# printing the new DataFrame
print("My new DataFrame")
df.loc[:,['Maths Score','Name','Sr.no']]
Python
输出:
方法3:通过传递一个列表来使用一个列的子集
例子1 :
# 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)
Python
输出:
例子2 :
# 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)
Python
输出 :
方法4:使用列表反转方法
这里我们将使用list reverse()方法来改变列的顺序。
# 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")
display(df)
cols = list(df.columns)
cols.reverse()
# printing the new DataFrame
print("My new DataFrame")
df[cols]
Python
输出: