2017-03-09 81 views
1

我目前正在从交叉表操作中处理数据帧。在熊猫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']它返回一个错误:

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

回答

0

你可以使用reindexreindex_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 
0

要使用的顺序列的列表中指定的大熊猫任何数据帧,只是索引的列你想:

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

由于它看起来好像.reindex_axis()为我工作,另一个继续返回错误。再次感谢。