我有以下DataFrame(df):

import numpy as np
import pandas as pd

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

我通过分配添加更多列:

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

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


当前回答

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

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

其他回答

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

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

简单地说,

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

您需要按所需的顺序创建一个新的列列表,然后使用df=df[cols]以新的顺序重新排列列。

cols = ['mean']  + [col for col in df if col != 'mean']
df = df[cols]

您也可以使用更通用的方法。在本例中,最后一列(由-1表示)作为第一列插入。

cols = [df.columns[-1]] + [col for col in df if col != df.columns[-1]]
df = df[cols]

如果DataFrame中存在列,也可以使用此方法按所需顺序重新排序列。

inserted_cols = ['a', 'b', 'c']
cols = ([col for col in inserted_cols if col in df] 
        + [col for col in df if col not in inserted_cols])
df = df[cols]

您可以使用以下名称列表对数据帧列进行重新排序:

df=df.filter(list_of_col_name)

这里有一个函数可以对任意数量的列执行此操作。

def mean_first(df):
    ncols = df.shape[1]        # Get the number of columns
    index = list(range(ncols)) # Create an index to reorder the columns
    index.insert(0,ncols)      # This puts the last column at the front
    return(df.assign(mean=df.mean(1)).iloc[:,index]) # new df with last column (mean) first