Pandas dict to dataframe - columns out of order?

前端 未结 2 655
死守一世寂寞
死守一世寂寞 2021-01-16 06:18

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         


        
相关标签:
2条回答
  • 2021-01-16 07:07

    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
    
    0 讨论(0)
  • 2021-01-16 07:08

    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.

    0 讨论(0)
提交回复
热议问题