我有以下DataFrame(df):

import numpy as np
import pandas as pd

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

我通过分配添加更多列:

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

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


当前回答

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

其他回答

此函数避免了您只需列出数据集中的每个变量来对其中的几个变量进行排序。

def order(frame,var):
    if type(var) is str:
        var = [var] #let the command take a string or list
    varlist =[w for w in frame.columns if w not in var]
    frame = frame[var+varlist]
    return frame 

它需要两个参数,第一个是数据集,第二个是要放到前面的数据集中的列。

所以在我的例子中,我有一个名为Frame的数据集,其中包含变量A1、A2、B1、B2、Total和Date。如果我想把道达尔带到前面,那么我所要做的就是:

frame = order(frame,['Total'])

如果我想将Total和Date带到前台,那么我会:

frame = order(frame,['Total','Date'])

编辑:

另一种有用的使用方法是,如果您有一个不熟悉的表,并且正在查找其中包含特定术语的变量,例如VAR1、VAR2,。。。您可以执行以下操作:

frame = order(frame,[v for v in frame.columns if "VAR" in v])

书中最黑客的方法

df.insert(0, "test", df["mean"])
df = df.drop(columns=["mean"]).rename(columns={"test": "mean"})

你也可以这样做:

df = df[['mean', '0', '1', '2', '3']]

您可以通过以下方式获取列列表:

cols = list(df.columns.values)

输出将产生:

['0', '1', '2', '3', 'mean']

…然后,在将其放入第一个函数之前,可以手动重新排列

我有一个在panda中重新排序列名的非常具体的用例。有时我在基于现有列的数据帧中创建一个新列。默认情况下,panda将在末尾插入我的新列,但我希望新列插入到它派生的现有列旁边。

def rearrange_list(input_list, input_item_to_move, input_item_insert_here):
    '''
    Helper function to re-arrange the order of items in a list.
    Useful for moving column in pandas dataframe.

    Inputs:
        input_list - list
        input_item_to_move - item in list to move
        input_item_insert_here - item in list, insert before 

    returns:
        output_list
    '''
    # make copy for output, make sure it's a list
    output_list = list(input_list)

    # index of item to move
    idx_move = output_list.index(input_item_to_move)

    # pop off the item to move
    itm_move = output_list.pop(idx_move)

    # index of item to insert here
    idx_insert = output_list.index(input_item_insert_here)

    # insert item to move into here
    output_list.insert(idx_insert, itm_move)

    return output_list


import pandas as pd

# step 1: create sample dataframe
df = pd.DataFrame({
    'motorcycle': ['motorcycle1', 'motorcycle2', 'motorcycle3'],
    'initial_odometer': [101, 500, 322],
    'final_odometer': [201, 515, 463],
    'other_col_1': ['blah', 'blah', 'blah'],
    'other_col_2': ['blah', 'blah', 'blah']
})
print('Step 1: create sample dataframe')
display(df)
print()

# step 2: add new column that is difference between final and initial
df['change_odometer'] = df['final_odometer']-df['initial_odometer']
print('Step 2: add new column')
display(df)
print()

# step 3: rearrange columns
ls_cols = df.columns
ls_cols = rearrange_list(ls_cols, 'change_odometer', 'final_odometer')
df=df[ls_cols]
print('Step 3: rearrange columns')
display(df)

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

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]