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:
panda
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
Python dictionary is an unordered structure, and the key order you get when printing it (or looping over its keys) is arbitrary.
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)
where column_order
is a list of column names in the order.