在pandas数据帧中排列列

2024-04-25 18:54:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在处理一个交叉表操作的数据帧。在

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

列的顺序如下

^{pr2}$

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

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 '

Tags: 数据lambdatruedatalen顺序allone
3条回答

再次感谢,.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

要指定pandas中任何数据帧的列,只需按所需顺序用列列表进行索引:

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

相关问题 更多 >