The to_csv method of pandas does not preserve the order of columns. It chooses to alphabetically arrange the columns in CSV. This is a bug and has been reported and is supposed to be corrected in version 0.11.0. I have 0.18.0.
import pandas as pd
df = pd.DataFrame({'V_pod_error' : [a],
'V_pod_used' : [b],
'U_sol_type' : [c]
...
... and so on upto 50 columns }
pd.to_csv(df)
Excel order:
0 U_sol type V_pod_error V_pod_used ...
1
What I want is order in the dictionary:
0 V_pod_error V_pod_used U_sol type ...
1
I have a huge number of columns and names. I cannot do it manually or write out the column order. There has been the exact same question in 2013 here. And it doesnt look like there is an update! I would like to ask the community to help me out! This is really problematic.
Pandas. DataFrame doesn't preserve the column order when converting from a DataFrames.
Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.
When you write pandas DataFrame to an existing CSV file, it overwrites the file with the new contents. To append a DataFrame to an existing CSV file, you need to specify the append write mode using mode='a' .
You can change the order of columns in the pandas dataframe using the df. reindex() method.
Try the following solution. Even I faced the same issue. I solved it as follows:
import pandas as pd
df = pd.DataFrame({'V_pod_error' : [a],
'V_pod_used' : [b],
'U_sol_type' : [c]
...
... and so on upto 50 columns }
column_order = ['V_pod_error', 'V_pod_used', 'U_sol_type',.....# upto 50 column names]
df[column_order].to_csv(file_name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With