我有以下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-选择添加删除

其他回答

如果列名太长,无法键入,则可以通过整数列表指定新顺序,其中包含以下位置:

数据:

          0         1         2         3         4      mean
0  0.397312  0.361846  0.719802  0.575223  0.449205  0.500678
1  0.287256  0.522337  0.992154  0.584221  0.042739  0.485741
2  0.884812  0.464172  0.149296  0.167698  0.793634  0.491923
3  0.656891  0.500179  0.046006  0.862769  0.651065  0.543382
4  0.673702  0.223489  0.438760  0.468954  0.308509  0.422683
5  0.764020  0.093050  0.100932  0.572475  0.416471  0.389390
6  0.259181  0.248186  0.626101  0.556980  0.559413  0.449972
7  0.400591  0.075461  0.096072  0.308755  0.157078  0.207592
8  0.639745  0.368987  0.340573  0.997547  0.011892  0.471749
9  0.050582  0.714160  0.168839  0.899230  0.359690  0.438500

通用示例:

new_order = [3,2,1,4,5,0]
print(df[df.columns[new_order]])  

          3         2         1         4      mean         0
0  0.575223  0.719802  0.361846  0.449205  0.500678  0.397312
1  0.584221  0.992154  0.522337  0.042739  0.485741  0.287256
2  0.167698  0.149296  0.464172  0.793634  0.491923  0.884812
3  0.862769  0.046006  0.500179  0.651065  0.543382  0.656891
4  0.468954  0.438760  0.223489  0.308509  0.422683  0.673702
5  0.572475  0.100932  0.093050  0.416471  0.389390  0.764020
6  0.556980  0.626101  0.248186  0.559413  0.449972  0.259181
7  0.308755  0.096072  0.075461  0.157078  0.207592  0.400591
8  0.997547  0.340573  0.368987  0.011892  0.471749  0.639745
9  0.899230  0.168839  0.714160  0.359690  0.438500  0.050582

虽然看起来我只是以不同的顺序显式键入列名,但列“mean”的事实应该清楚地表明,new_order与实际位置相关,而不是列名。

对于OP问题的具体情况:

new_order = [-1,0,1,2,3,4]
df = df[df.columns[new_order]]
print(df)

       mean         0         1         2         3         4
0  0.500678  0.397312  0.361846  0.719802  0.575223  0.449205
1  0.485741  0.287256  0.522337  0.992154  0.584221  0.042739
2  0.491923  0.884812  0.464172  0.149296  0.167698  0.793634
3  0.543382  0.656891  0.500179  0.046006  0.862769  0.651065
4  0.422683  0.673702  0.223489  0.438760  0.468954  0.308509
5  0.389390  0.764020  0.093050  0.100932  0.572475  0.416471
6  0.449972  0.259181  0.248186  0.626101  0.556980  0.559413
7  0.207592  0.400591  0.075461  0.096072  0.308755  0.157078
8  0.471749  0.639745  0.368987  0.340573  0.997547  0.011892
9  0.438500  0.050582  0.714160  0.168839  0.899230  0.359690

这种方法的主要问题是多次调用同一代码将每次产生不同的结果,因此需要小心:)

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

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])

我尝试了创建一个order函数,您可以使用Stata的order命令对列进行重新排序/移动。最好创建一个py文件(其名称可能是order.py),并将其保存在目录中并调用它的函数

def order(dataframe,cols,f_or_l=None,before=None, after=None):

#만든이: 김완석, Stata로 뚝딱뚝딱 저자, blog.naver.com/sanzo213 운영
# 갖다 쓰시거나 수정을 하셔도 되지만 출처는 꼭 밝혀주세요
# cols옵션 및 befor/after옵션에 튜플이 가능하게끔 수정했으며, 오류문구 수정함(2021.07.12,1)
# 칼럼이 멀티인덱스인 상태에서 reset_index()메소드 사용했을 시 적용안되는 걸 수정함(2021.07.12,2) 

import pandas as pd
if (type(cols)==str) or (type(cols)==int) or (type(cols)==float) or (type(cols)==bool) or type(cols)==tuple:    
    cols=[cols]
    
dd=list(dataframe.columns)
for i in cols:
    i
    dd.remove(i) #cols요소를 제거함
    
if (f_or_l==None) & ((before==None) & (after==None)):
    print('f_or_l옵션을 쓰시거나 아니면 before옵션/after옵션 쓰셔야되요')
    
if ((f_or_l=='first') or (f_or_l=='last')) & ~((before==None) & (after==None)):
    print('f_or_l옵션 사용시 before after 옵션 사용불가입니다.')
    
if (f_or_l=='first') & (before==None) & (after==None):
    new_order=cols+dd
    dataframe=dataframe[new_order]
    return dataframe

if (f_or_l=='last') & (before==None) & (after==None):   
    new_order=dd+cols
    dataframe=dataframe[new_order]
    return dataframe
    
if (before!=None) & (after!=None):
    print('before옵션 after옵션 둘다 쓸 수 없습니다.')
    

if (before!=None) & (after==None) & (f_or_l==None):

    if not((type(before)==str) or (type(before)==int) or (type(before)==float) or
       (type(before)==bool) or ((type(before)!=list)) or 
       ((type(before)==tuple))):
        print('before옵션은 칼럼 하나만 입력가능하며 리스트 형태로도 입력하지 마세요.')
    
    else:
        b=dd[:dd.index(before)]
        a=dd[dd.index(before):]
        
        new_order=b+cols+a
        dataframe=dataframe[new_order]  
        return dataframe
    
if (after!=None) & (before==None) & (f_or_l==None):

    if not((type(after)==str) or (type(after)==int) or (type(after)==float) or
       (type(after)==bool) or ((type(after)!=list)) or 
       ((type(after)==tuple))):
            
        print('after옵션은 칼럼 하나만 입력가능하며 리스트 형태로도 입력하지 마세요.')  

    else:
        b=dd[:dd.index(after)+1]
        a=dd[dd.index(after)+1:]
        
        new_order=b+cols+a
        dataframe=dataframe[new_order]
        return dataframe

下面的python代码是我制作的order函数的一个示例。我希望您可以使用我的order函数轻松地对列进行重新排序:)

# module

import pandas as pd
import numpy as np
from order import order # call order function from order.py file

# make a dataset

columns='a b c d e f g h i j k'.split()
dic={}

n=-1
for i in columns:
    
    n+=1
    dic[i]=list(range(1+n,10+1+n))
data=pd.DataFrame(dic)
print(data)

# use order function (1) : order column e in the first

data2=order(data,'e',f_or_l='first')
print(data2)

# use order function (2): order column e in the last , "data" dataframe

print(order(data,'e',f_or_l='last'))


# use order function (3) : order column i before column c in "data" dataframe

print(order(data,'i',before='c'))


# use order function (4) : order column g after column b in "data" dataframe

print(order(data,'g',after='b'))

# use order function (4) : order columns ['c', 'd', 'e'] after column i in "data" dataframe

print(order(data,['c', 'd', 'e'],after='i'))

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

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]

大多数答案都不够概括,panda reindex_axis方法有点乏味,因此我提供了一个简单的函数,可以使用字典将任意数量的列移动到任意位置,其中key=列名,value=要移动到的位置。如果数据帧很大,请将True传递给“big_data”,那么函数将返回有序的列列表。您可以使用此列表来分割数据。

def order_column(df, columns, big_data = False):

    """Re-Orders dataFrame column(s)
       Parameters : 
       df      -- dataframe
       columns -- a dictionary:
                  key   = current column position/index or column name
                  value = position to move it to  
       big_data -- boolean 
                  True = returns only the ordered columns as a list
                          the user user can then slice the data using this
                          ordered column
                  False = default - return a copy of the dataframe
    """
    ordered_col = df.columns.tolist()

    for key, value in columns.items():

        ordered_col.remove(key)
        ordered_col.insert(value, key)

    if big_data:

        return ordered_col

    return df[ordered_col]

# e.g.
df = pd.DataFrame({'chicken wings': np.random.rand(10, 1).flatten(), 'taco': np.random.rand(10,1).flatten(),
                          'coffee': np.random.rand(10, 1).flatten()})
df['mean'] = df.mean(1)

df = order_column(df, {'mean': 0, 'coffee':1 })

>>>

col = order_column(df, {'mean': 0, 'coffee':1 }, True)

col
>>>
['mean', 'coffee', 'chicken wings', 'taco']

# you could grab it by doing this

df = df[col]