在 pandas DataFrame 中排列列

Arranging columns in a pandas DataFrame

我目前正在处理来自交叉表操作的数据框。

pd.crosstab(data['One'],data['two'], margins=True).apply(lambda r: r/len(data)*100,axis = 1)

列按以下顺序出现

A   B  C  D  E  All
B   
C   
D   
E
All             100

但我希望列的顺序如下所示:

A    C  D  B  E All
B
C
D
E
All             100

有没有一种简单的方法来组织列? 当我使用 colnames=['C', 'D','B','E'] 它 returns 一个错误:

'AssertionError: arrays and names must have the same length '

要在 pandas 中指定任何数据框的列,只需按您想要的顺序使用列列表进行索引:

columns = ['A', 'C', 'D', 'B', 'E', 'All']
df2 = df.loc[:, columns]
print(df2)

您可以使用 reindex or reindex_axis 或按 subset 更改顺序:

colnames=['C', 'D','B','E']
new_cols = colnames + ['All']

#solution 1 change ordering by reindexing
df1 = df.reindex_axis(new_cols,axis=1)
#solution 2 change ordering by reindexing
df1 = df.reindex(columns=new_cols)
#solution 3 change order by subset
df1 = df[new_cols]

print (df1)
    C   D   B   E    All
0 NaN NaN NaN NaN    NaN
1 NaN NaN NaN NaN    NaN
2 NaN NaN NaN NaN    NaN
3 NaN NaN NaN NaN    NaN
4 NaN NaN NaN NaN  100.0