我有以下DataFrame(df):

import numpy as np
import pandas as pd

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

我通过分配添加更多列:

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

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


当前回答

使用T怎么样?

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

其他回答

import numpy as np
import pandas as pd
df = pd.DataFrame()
column_names = ['x','y','z','mean']
for col in column_names: 
    df[col] = np.random.randint(0,100, size=10000)

您可以尝试以下解决方案:

解决方案1:

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

解决方案2:


df = df[['mean', 'x', 'y', 'z']]

解决方案3:

col = df.pop("mean")
df = df.insert(0, col.name, col)

解决方案4:

df.set_index(df.columns[-1], inplace=True)
df.reset_index(inplace=True)

解决方案5:

cols = list(df)
cols = [cols[-1]] + cols[:-1]
df = df[cols]

解决方案6:

order = [1,2,3,0] # setting column's order
df = df[[df.columns[i] for i in order]]

时间比较:

解决方案1:

CPU时间:用户1.05 ms,sys:35µs,总计:1.08 ms壁时间:995µs

解决方案2:

CPU时间:用户933µs,系统:0 ns,总计:933µ壁时间:800µs

解决方案3:

CPU时间:用户0 ns,sys:1.35 ms,总计:1.35 ms壁时间:1.08 ms

解决方案4:

CPU时间:用户1.23毫秒,系统:45µs,总计:1.27毫秒壁时间:986µs

解决方案5:

CPU时间:用户1.09 ms,系统:19µs,总计:1.11 ms壁时间:949µs

解决方案6:

CPU时间:用户955µs,系统:34µs,总计:989µs壁时间:859µs

熊猫>=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-选择添加删除

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

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

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

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

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

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

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

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

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]