Why does the pandas the dataframe column order change automatically?

后端 未结 2 1666
傲寒
傲寒 2021-01-27 10:11

When I were output the result to CSV file, I generated a pandas dataframe. But the dataframe column order changed automatically, I am curious Why would this happened?

2条回答
  •  情书的邮戳
    2021-01-27 10:59

    As Youn Elan pointed out, python dictionaries aren't ordered, so if you use a dictionary to provide your data, the columns will end up randomly ordered. You can use the columns argument to set the order of the columns explicitly though:

    import pandas as pd
    
    before = pd.DataFrame({'lake_id': range(3), 'area': (['a', 'b', 'c'])})
    print 'before'
    print before
    
    after = pd.DataFrame({'lake_id': range(3), 'area': (['a', 'b', 'c'])},
                         columns=['lake_id', 'area'])
    print 'after'
    print after
    

    Result:

    before
      area  lake_id
    0    a        0
    1    b        1
    2    c        2
    after
       lake_id area
    0        0    a
    1        1    b
    2        2    c
    

提交回复
热议问题