设置pandas数据框中的列顺序 [英] Set order of columns in pandas dataframe

查看:101
本文介绍了设置pandas数据框中的列顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以根据我的个人喜好(即不是按字母或数字排序,而是更像遵循某些约定)对熊猫数据框中的列进行重新排序?

Is there a way to reorder columns in pandas dataframe based on my personal preference (i.e. not alphabetically or numerically sorted, but more like following certain conventions)?

简单的例子:

frame = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']})

产生此:

   one thing other thing  second thing
0          1           a           0.1
1          2           e           0.2
2          3           i           1.0
3          4           o           2.0

但是,我想要这样:

   one thing second thing  other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o

(请提供通用的解决方案,而不是针对此情况.非常感谢.)

(Please, provide a generic solution rather than specific to this case. Many thanks.)

推荐答案

只需输入列名称即可自己选择订单.请注意双括号:

Just select the order yourself by typing in the column names. Note the double brackets:

frame = frame[['column I want first', 'column I want second'...etc.]]

这篇关于设置pandas数据框中的列顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆