pandas 为什么数据框的列顺序会自动更改? [英] Why does the pandas the dataframe column order change automatically?

查看:88
本文介绍了 pandas 为什么数据框的列顺序会自动更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将结果输出到CSV文件时,我生成了一个熊猫数据框。但是数据框的列顺序会自动更改,我很好奇为什么会发生这种情况?

When I were output the result to CSV file, I generated a pandas dataframe. But the dataframe column order changed automatically, I am curious Why would this happened?

问题图片:

推荐答案

正如尤恩·埃伦(Yun Elan)指出的那样,python字典没有排序,因此,如果您使用字典来提供数据,则这些列将最终随机排序。您可以使用参数来显式设置列的顺序:

As Youn Elan pointed out, python dictionaries aren't ordered, so if you use a dictionary to provide your data, the columns will end up randomly ordered. You can use the columns argument to set the order of the columns explicitly though:

import pandas as pd

before = pd.DataFrame({'lake_id': range(3), 'area': (['a', 'b', 'c'])})
print 'before'
print before

after = pd.DataFrame({'lake_id': range(3), 'area': (['a', 'b', 'c'])},
                     columns=['lake_id', 'area'])
print 'after'
print after

结果:

before
  area  lake_id
0    a        0
1    b        1
2    c        2
after
   lake_id area
0        0    a
1        1    b
2        2    c

这篇关于 pandas 为什么数据框的列顺序会自动更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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