pandas 熊猫如何交换或重新排序列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53141240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:07:57  来源:igfitidea点击:

pandas how to swap or reorder columns

pythonpandasmultiple-columnsswap

提问by Yun Tae Hwang

I know that there are ways to swap the column order in python pandas. Let say I have this example dataset:

我知道有一些方法可以在 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)[email protected]', '(F)312-533-2442 [email protected]']}

df = pd.DataFrame(employee)

The one basic way to do would be:

一种基本的方法是:

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

However, as you can see, I only want to swap two columns. It was doable just because there are only 4 column, but what if I have like 100 columns? what would be an effective way to swap or reorder columns?

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

There might be 2 cases:

可能有2种情况:

  1. when you just want 2 columns swapped.
  2. when you want 3 columns reordered. (I am pretty sure that this case can be applied to more than 3 columns.)
  1. 当您只想交换 2 列时。
  2. 当您想要重新排序 3 列时。(我很确定这种情况可以应用于 3 列以上。)

Thank you guys.

谢谢你们。

回答by sanster9292

Say your current order of column is [b,c,d,a] and you want to order it into [a,b,c,d], you could do it this way:

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

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

回答by Vivek Kalyanarangan

Two column Swapping

两列交换

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

Reorder column Swapping (2 swaps)

重新排序列交换(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]

Swapping Multiple

交换多个

Now it comes down to how you can play with list slices -

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

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