Preserving Column Order - Python Pandas and Column Concat

前端 未结 1 1330
生来不讨喜
生来不讨喜 2021-02-03 10:22

So my google-fu doesn\'t seem to be doing me justice with what seems like should be a trivial procedure.

In Pandas for Python I have 2 datasets, I want to merge them. T

相关标签:
1条回答
  • 2021-02-03 11:03

    Assuming the concatenated DataFrame is df, you can perform the reordering of columns as follows:

    important = ['Username', 'Name']
    reordered = important + [c for c in df.columns if c not in important]
    df = df[reordered]
    print df
    

    Output:

         Username   Name Alias1 Alias2
    0  Tomfoolery    Tom    TJZ    NaN
    1     MsMeryl  Meryl    Mer    NaN
    2     Midsize  Timmy   Yoda    NaN
    0    Firedbob    Bob   Fire  Gingy
    1  Tomfoolery    Tom    TJZ   Awww
    

    The list of numbers [0, 1, 2, 0, 1] is the index of the DataFrame. To prevent them from being written to the output file, you can use the index=False option in to_csv():

    df.to_csv('Result.csv', index=False, sep=' ')
    
    0 讨论(0)
提交回复
热议问题