I have a python dict that has the format
dict = {
D:""
B:""
A:""
C:""
}
However, when I write this dict to a csv file in excel, the columns are rearranged to
A B C D
How do I keep the order of my dict in python when I write to excel?
writer = pd.ExcelWriter('list_of_detected_words.xlsx', engine='xlsxwriter')
list_of_detected_words = pd.DataFrame.from_records(form_info)
list_of_detected_words.to_excel(writer, "Sheet1",startrow=1)
Above is the code that writes to excel.
Another way to reorder columns is to use the Pandas . reindex() method. This allows you to pass in the columns= parameter to pass in the order of columns that you want to use.
Sorting the Columns of Your DataFrame You can also use the column labels of your DataFrame to sort row values. Using . sort_index() with the optional parameter axis set to 1 will sort the DataFrame by the column labels. The sorting algorithm is applied to the axis labels instead of to the actual data.
You can sort pandas DataFrame by one or multiple (one or more) columns using sort_values() method and by ascending or descending order. To specify the order, you have to use ascending boolean property; False for descending and True for ascending. By default, it is set to True.
In the above example, we have used the select() function provided by the dplyr package to reorder columns of the dataframe named dataframe1 . Here, inside select() , dataframe1 - a dataframe whose column is to be reordered.
Contrary to what was mentioned above, the pandas.DataFrame.to_excel() function has a parameter that lets you set which order columns are written to your excel sheet. The parameter is
columns=[listOfColumns]
For my example above I would do
list_of_detected_words.to_excel(writer, "Sheet1", startrow=1, columns=[D,B,A,C] )
Documentation can be found on the following link.
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html
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