2017-03-09 80 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()爲我工作,另一個繼續返回錯誤。再次感謝。