我有以下DataFrame(df):

import numpy as np
import pandas as pd

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

我通过分配添加更多列:

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

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


当前回答

您可以执行以下操作(从Aman的答案中借用零件):

cols = df.columns.tolist()
cols.insert(0, cols.pop(-1))

cols
>>>['mean', 0L, 1L, 2L, 3L, 4L]

df = df[cols]

其他回答

我有一个在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)
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

只需按所需顺序分配列名:

In [39]: df
Out[39]: 
          0         1         2         3         4  mean
0  0.172742  0.915661  0.043387  0.712833  0.190717     1
1  0.128186  0.424771  0.590779  0.771080  0.617472     1
2  0.125709  0.085894  0.989798  0.829491  0.155563     1
3  0.742578  0.104061  0.299708  0.616751  0.951802     1
4  0.721118  0.528156  0.421360  0.105886  0.322311     1
5  0.900878  0.082047  0.224656  0.195162  0.736652     1
6  0.897832  0.558108  0.318016  0.586563  0.507564     1
7  0.027178  0.375183  0.930248  0.921786  0.337060     1
8  0.763028  0.182905  0.931756  0.110675  0.423398     1
9  0.848996  0.310562  0.140873  0.304561  0.417808     1

In [40]: df = df[['mean', 4,3,2,1]]

现在,“mean”列出现在前面:

In [41]: df
Out[41]: 
   mean         4         3         2         1
0     1  0.190717  0.712833  0.043387  0.915661
1     1  0.617472  0.771080  0.590779  0.424771
2     1  0.155563  0.829491  0.989798  0.085894
3     1  0.951802  0.616751  0.299708  0.104061
4     1  0.322311  0.105886  0.421360  0.528156
5     1  0.736652  0.195162  0.224656  0.082047
6     1  0.507564  0.586563  0.318016  0.558108
7     1  0.337060  0.921786  0.930248  0.375183
8     1  0.423398  0.110675  0.931756  0.182905
9     1  0.417808  0.304561  0.140873  0.310562

这里有一个非常简单的答案(只有一行)。

在将“n”列添加到df中之后,可以执行以下操作。

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))
df['mean'] = df.mean(1)
df
           0           1           2           3           4        mean
0   0.929616    0.316376    0.183919    0.204560    0.567725    0.440439
1   0.595545    0.964515    0.653177    0.748907    0.653570    0.723143
2   0.747715    0.961307    0.008388    0.106444    0.298704    0.424512
3   0.656411    0.809813    0.872176    0.964648    0.723685    0.805347
4   0.642475    0.717454    0.467599    0.325585    0.439645    0.518551
5   0.729689    0.994015    0.676874    0.790823    0.170914    0.672463
6   0.026849    0.800370    0.903723    0.024676    0.491747    0.449473
7   0.526255    0.596366    0.051958    0.895090    0.728266    0.559587
8   0.818350    0.500223    0.810189    0.095969    0.218950    0.488736
9   0.258719    0.468106    0.459373    0.709510    0.178053    0.414752


### here you can add below line and it should work 
# Don't forget the two (()) 'brackets' around columns names.Otherwise, it'll give you an error.

df = df[list(('mean',0, 1, 2,3,4))]
df

        mean           0           1           2           3           4
0   0.440439    0.929616    0.316376    0.183919    0.204560    0.567725
1   0.723143    0.595545    0.964515    0.653177    0.748907    0.653570
2   0.424512    0.747715    0.961307    0.008388    0.106444    0.298704
3   0.805347    0.656411    0.809813    0.872176    0.964648    0.723685
4   0.518551    0.642475    0.717454    0.467599    0.325585    0.439645
5   0.672463    0.729689    0.994015    0.676874    0.790823    0.170914
6   0.449473    0.026849    0.800370    0.903723    0.024676    0.491747
7   0.559587    0.526255    0.596366    0.051958    0.895090    0.728266
8   0.488736    0.818350    0.500223    0.810189    0.095969    0.218950
9   0.414752    0.258719    0.468106    0.459373    0.709510    0.178053

我尝试了创建一个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'))