本文介绍了Pandas dict to dataframe - 列乱序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了搜索,但没有看到与此特定问题有关的任何结果.我有一个 Python dict,正在将我的 dict 转换为 pandas 数据框:

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 dict 的顺序不同.我不确定大熊猫是如何重新排序的.我如何保留订单?

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 词典(3.6 之前的版本)是无序的,因此不能依赖列顺序.之后您可以简单地设置列顺序.

Python dictionaries (pre 3.6) are unordered so the column order can not be relied upon. You can simply set the column order afterwards.

In [1]:

df = pd.DataFrame({'a':np.random.rand(5),'b':np.random.randn(5)})
df
Out[1]:
          a         b
0  0.512103 -0.102990
1  0.762545 -0.037441
2  0.034237  1.343115
3  0.667295 -0.814033
4  0.372182  0.810172
In [2]:

df = df[['b','a']]
df
Out[2]:
          b         a
0 -0.102990  0.512103
1 -0.037441  0.762545
2  1.343115  0.034237
3 -0.814033  0.667295
4  0.810172  0.372182

这篇关于Pandas dict to dataframe - 列乱序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:28
查看更多