Why does the pandas the dataframe column order change automatically?

后端 未结 2 1628
傲寒
傲寒 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
    
    0 讨论(0)
  • 2021-01-27 11:06

    I notice you use a dictionary.

    Dictionaries in python are not garanteed to be in any order. It depends on multiple factors, including what's in the array. Keys are garanteed to be unique though

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