Pandas dict to dataframe - columns out of order?

前端 未结 2 656
死守一世寂寞
死守一世寂寞 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条回答
  •  梦毁少年i
    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
    

提交回复
热议问题