pandas 如何交换或重新排序列

pandas how to swap or reorder columns

我知道有一些方法可以交换 python pandas 中的列顺序。 假设我有这个示例数据集:

import pandas as pd    
employee = {'EmployeeID' : [0,1,2],
     'FirstName' : ['a','b','c'],
     'LastName' : ['a','b','c'],
     'MiddleName' : ['a','b', None],
     'Contact' : ['(M) 133-245-3123', '(F)a123@gmail.com', '(F)312-533-2442 jimmy234@gmail.com']}

df = pd.DataFrame(employee)

一种基本的方法是:

neworder = ['EmployeeID','FirstName','MiddleName','LastName','Contact']
df=df.reindex(columns=neworder)

但是,如您所见,我只想交换两列。这是可行的,因为只有 4 列,但如果我有 100 列呢?交换或重新排序列的有效方法是什么?

可能有2种情况:

  1. 当您只想交换 2 列时。
  2. 当您想要对 3 列重新排序时。 (我很确定这种情况可以应用于 3 列以上。)

两列交换

cols = list(df.columns)
a, b = cols.index('LastName'), cols.index('MiddleName')
cols[b], cols[a] = cols[a], cols[b]
df = df[cols]

重新排序列交换(2 次交换)

cols = list(df.columns)
a, b, c, d = cols.index('LastName'), cols.index('MiddleName'), cols.index('Contact'), cols.index('EmployeeID')
cols[a], cols[b], cols[c], cols[d] = cols[b], cols[a], cols[d], cols[c]
df = df[cols]

交换倍数

现在归结为如何使用列表切片 -

cols = list(df.columns)
cols = cols[1::2] + cols[::2]
df = df[cols]

假设您当前的列顺序是 [b,c,d,a],并且您想将其排序为 [a,b,c,d],您可以这样做:

new_df = old_df[['a', 'b', 'c', 'd']]

当在更大范围内遇到同样的问题时,我在 link: http://www.datasciencemadesimple.com/re-arrange-or-re-order-the-column-of-dataframe-in-pandas-python-2/ 标题下遇到了一个非常优雅的解决方案 "Rearrange the column of dataframe by column position in pandas python".

基本上,如果您将列顺序作为列表,则可以将其作为新的列顺序读取。

##### Rearrange the column of dataframe by column position in pandas python

df2=df1[df1.columns[[3,2,1,0]]]
print(df2)

就我而言,我有一个 pre-calculated 列 linkage 来确定我想要的新顺序。如果这个顺序在L中被定义为一个数组,那么:

a_L_order = a[a.columns[L]]

如果你想在开头有一个固定的列列表,你可以这样做

cols = ['EmployeeID','FirstName','MiddleName','LastName']
df = df[cols + [c for c in df.columns if c not in cols]]

这会将这 4 列放在最前面,其余的保持不变(没有任何重复的列)。

写入文件时

当数据框被写入文件(例如 CSV)时,列也可以重新排序:

df.to_csv('employees.csv',
          columns=['EmployeeID','FirstName','MiddleName','LastName','Contact'])

当您没有太多列并且不想列出列名时,一种对列重新排序的简洁方法是 .iloc[].

df_reorderd = df.iloc[:, [0, 1, 3, 2, 4]]