pandas dicto到数据框-列是否乱序? [英] Pandas dicto to dataframe - columns out of order?
问题描述
我进行了搜索,但没有发现与此特定问题相关的任何结果.我有一个Python字典,并将我的字典转换为熊猫数据框:
I did a search but didn't see any results pertaining to this specific question. I have a Python dict, and am converting my dict to a pandas dataframe:
pandas.DataFrame(data_dict)
它有效,只有一个问题-我的pandas数据框的列与我的python字典的顺序不同.我不确定熊猫如何重新排序.如何保留订单?
It works, with only one problem - the columns of my pandas dataframe are not in the same order as my Python dict. I'm not sure how pandas is reordering things. How do I retain the ordering?
推荐答案
Python字典是无序结构,在打印(或遍历其键)时获得的键顺序是任意的.
Python dictionary is an unordered structure, and the key order you get when printing it (or looping over its keys) is arbitrary.
在这种情况下,您需要使用以下方式显式指定DataFrame中的列顺序:
In this case, you would need to explicitly specify the order of columns in the DataFrame with,
pandas.DataFrame(data=data_dict, columns=columns_order)
其中column_order
是按顺序列出的列名.
where column_order
is a list of column names in the order.
这篇关于 pandas dicto到数据框-列是否乱序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!