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 |
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 |
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 |
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.
- Test whether Column Name Exists in pandas DataFrame in Python
- Exchange NaN Values in Column of pandas DataFrame by 0 in Python
- Calculate Column & Row Sums of pandas DataFrame in Python
- Identify Column Indices in pandas DataFrame in Python
- Add Indices of pandas DataFrame as New Column in Python
- Count Distinct Values by Group of pandas DataFrame Column in Python