代码之家  ›  专栏  ›  技术社区  ›  00__00__00

pandas中特定列的强制排序

  •  1
  • 00__00__00  · 技术社区  · 7 年前

    我有一个包含许多列的数据帧。

    df=pd.DataFrame(data=np.random.rand(100,1000))
    

    [793] [642] 作为第一个,而其他的顺序并不重要。

    我能做到

    df.columns=[793,642,...the rest...]
    

    1 回复  |  直到 7 年前
        1
  •  3
  •   jezrael    7 年前

    使用 difference 对于所有未在具有前置列表的列表中指定的列 L 对于新列名,上次更改按子集排序 [] :

    df=pd.DataFrame(data=np.random.rand(100,1000))
    
    L = [793, 642]
    
    cols = L + df.columns.difference(L).tolist()
    #another solution
    #cols = np.concatenate([L, df.columns.difference(L)])
    #list comprehension solution
    #cols = L + [x for x in df.columns if not x in L]
    
    df = df[cols]
    print (df.head(2))
            793       642       0         1         2         3         4    \
    0  0.462103  0.811223  0.491396  0.701752  0.494450  0.352717  0.345460   
    1  0.840597  0.852080  0.681095  0.014459  0.963252  0.972862  0.490964   
    
            5         6         7      ...          990       991       992  \
    0  0.718141  0.199168  0.379924    ...     0.279972  0.963898  0.987907   
    1  0.151226  0.625833  0.428249    ...     0.069179  0.045112  0.328453   
    
            993       994       995       996       997       998       999  
    0  0.402805  0.243648  0.624790  0.864440  0.653621  0.066524  0.072025  
    1  0.894080  0.451285  0.538485  0.834018  0.926311  0.032849  0.095636  
    
    [2 rows x 1000 columns]