我有以下DataFrame(df):

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))

我通过分配添加更多列:

df['mean'] = df.mean(1)

如何将列的意思移到前面,即将其设置为第一列,而其他列的顺序保持不变?


当前回答

在您的情况下,

df = df.reindex(columns=['mean',0,1,2,3,4])

会做你想做的事。

在我的情况下(一般形式):

df = df.reindex(columns=sorted(df.columns))
df = df.reindex(columns=(['opened'] + list([a for a in df.columns if a != 'opened']) ))

其他回答

只需键入要更改的列名,然后为新位置设置索引。

def change_column_order(df, col_name, index):
    cols = df.columns.tolist()
    cols.remove(col_name)
    cols.insert(index, col_name)
    return df[cols]

对于您的情况,这将是:

df = change_column_order(df, 'mean', 0)

熊猫>=1.3(2022年编辑):

df.insert(0, 'mean', df.pop('mean'))

怎么样(对于熊猫<1.3,原始答案)

df.insert(0, 'mean', df['mean'])

https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#column-选择添加删除

使用T怎么样?

df = df.T.reindex(['mean', 0, 1, 2, 3, 4]).T

这里有一种移动一个现有列的方法,它将修改现有的数据帧。

my_column = df.pop('column name')
df.insert(3, my_column.name, my_column)  # Is in-place

我自己也遇到了一个类似的问题,只是想补充一下我已经解决的问题。我喜欢用于更改列顺序的reindex_axis()方法。这是有效的:

df = df.reindex_axis(['mean'] + list(df.columns[:-1]), axis=1)

另一种基于@Jorge评论的方法:

df = df.reindex(columns=['mean'] + list(df.columns[:-1]))

虽然reindex_axis在微基准测试中似乎比reindex稍快,但我认为我更喜欢后者,因为它的直接性。