Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Write to Excel rearranging columns based on alphabetic order

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.

like image 260
M Waz Avatar asked Feb 14 '18 20:02

M Waz


People also ask

How do I rearrange column order in pandas?

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.

How do you sort a column in alphabetical order in a DataFrame?

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.

How do I sort columns in pandas DataFrame?

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.

Which function is used to rearrange columns in DataFrame?

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.


1 Answers

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

like image 87
M Waz Avatar answered Oct 04 '22 17:10

M Waz