我有以下DataFrame(df):

import numpy as np
import pandas as pd

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

我通过分配添加更多列:

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

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


当前回答

我认为这个函数更简单。您只需在开始或结束处或同时指定列的子集:

def reorder_df_columns(df, start=None, end=None):
    """
        This function reorder columns of a DataFrame.
        It takes columns given in the list `start` and move them to the left.
        Its also takes columns in `end` and move them to the right.
    """
    if start is None:
        start = []
    if end is None:
        end = []
    assert isinstance(start, list) and isinstance(end, list)
    cols = list(df.columns)
    for c in start:
        if c not in cols:
            start.remove(c)
    for c in end:
        if c not in cols or c in start:
            end.remove(c)
    for c in start + end:
        cols.remove(c)
    cols = start + cols + end
    return df[cols]

其他回答

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

df=df.filter(list_of_col_name)

DataFrame.sort_index(axis=1)非常干净。请在此处检查文档。然后凹入

这个问题以前已经回答过,但reindex_axis现在已被弃用,因此我建议使用:

df = df.reindex(sorted(df.columns), axis=1)

对于那些想要指定他们想要的顺序而不是仅仅对它们进行排序的人来说,下面列出了解决方案:

df = df.reindex(['the','order','you','want'], axis=1)

现在,如何对列名列表排序真的不是熊猫问题,而是Python列表操作问题。有很多方法可以做到这一点,我认为这个答案有一个非常简洁的方法。

您需要按所需的顺序创建一个新的列列表,然后使用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.columns上使用.rendex:

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