Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用列名更改DataFrame列的顺序_Python_Python 2.7_Dataframe - Fatal编程技术网

Python 使用列名更改DataFrame列的顺序

Python 使用列名更改DataFrame列的顺序,python,python-2.7,dataframe,Python,Python 2.7,Dataframe,我需要将第三列移到列列表的末尾。这可以通过以下方式完成: cols = df.columns.tolist() cols = cols[0:2] + cols[4:] + cols[3] df= df[cols] 然而,如果我不知道我感兴趣的列的索引该怎么办。假设我只知道名为MyMagicCol的列应该移动到列列表的末尾。 我该怎么做呢?如果你想在一个列表中做,并且你知道你感兴趣的列的名称,你可以这样做 cols = [c for c in df.columns if c != 'MyMagi

我需要将第三列移到列列表的末尾。这可以通过以下方式完成:

cols = df.columns.tolist()
cols = cols[0:2] + cols[4:] + cols[3]
df= df[cols]
然而,如果我不知道我感兴趣的列的索引该怎么办。假设我只知道名为
MyMagicCol
的列应该移动到列列表的末尾。
我该怎么做呢?

如果你想在一个列表中做,并且你知道你感兴趣的列的名称,你可以这样做

cols = [c for c in df.columns if c != 'MyMagicCol'] + ['MyMagicCol']
df = df[cols]

如果您想直接使用列,也可以使用列名对数据帧进行切片。

如果您想在列表中执行此操作,并且知道您感兴趣的列的名称,您可以这样做

cols = [c for c in df.columns if c != 'MyMagicCol'] + ['MyMagicCol']
df = df[cols]
如果您想直接使用列,还可以使用列名称对数据帧进行切片