Change Column Order when Saving pandas DataFrame as CSV in Python (Example Code)

In this tutorial you’ll learn how to change the column order when saving a pandas DataFrame as a CSV file in the Python programming language.

Setting up the Example

import pandas as pd                                        # Import pandas library
my_df = pd.DataFrame({'C':range(20, 25),                   # Construct pandas DataFrame in Python
                      'B':['x', 'y', 'y', 'x', 'y'],
                      'D':['a', 's', 'd', 'f', 'g'],
                      'A':range(15, 10, - 1)})
print(my_df)
#     C  B  D   A
# 0  20  x  a  15
# 1  21  y  s  14
# 2  22  y  d  13
# 3  23  x  f  12
# 4  24  y  g  11

Example: Manually Adjust Order of Columns when Exporting pandas DataFrame to CSV File

my_df.to_csv('my_df.csv', columns = ['A', 'B', 'C', 'D'])  # Change order of variables
#     A  B   C  D
# 0  15  x  20  a
# 1  14  y  21  s
# 2  13  y  22  d
# 3  12  x  23  f
# 4  11  y  24  g

Further Resources

In the following, you can find some additional resources on topics such as counting, groups, and naming data.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top