简体   繁体   中英

Panda append and concat reorders the dataframe?

I created an empty dataframe (df1) with the python pandas package, only containing the columns: [var1, var2, var3]

I also have another dataframe (df2) which looks like this: columns: [var 2, var1, var3] values: [1, 2, 3]

When I append df2 to df1 the orders of the columns in the dataframe change. I tried to reorder the dataframe with the old list of columns with sort_values and sort, but it didn't work. Does anyone know how I can solve it? I am using python version 2.7

If I'm understanding this correctly, append is not a problem. It is only about column order. To change the order of columns in a Dataframe , simply slice with column names.

df1 = pds.DataFrame(columns=['var1', 'var2', 'var3'])     # desired order

# generate a disordered df somehow
df_disordered = pds.DataFrame(columns=['var2', 'var1', 'var3'])        
df_adjusted = df_disordered[df1.columns]          # slice with column names 
                                                  # or explicitly df_disordered[['var1', 'var2', 'var3']]

# now df_adjusted has the same column order as df1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM