how to switch the position of a columns in a df in python

To switch the position of columns in a dataframe in Python using pandas, you can use the reindex method and provide a new order for the columns. Here's an example:

main.py
import pandas as pd

# Create a sample dataframe
data = {'A': [1, 2, 3], 'B': ['a', 'b', 'c'], 'C': [10, 20, 30]}
df = pd.DataFrame(data)

# Print the original dataframe
print("Original DataFrame:")
print(df)

# Specify the desired column order
new_column_order = ['C', 'A', 'B']

# Reindex the dataframe with the new column order
df = df.reindex(columns=new_column_order)

# Print the updated dataframe
print("\nDataFrame with switched column positions:")
print(df)
467 chars
20 lines

Output:

main.py
Original DataFrame:
   A  B   C
0  1  a  10
1  2  b  20
2  3  c  30

DataFrame with switched column positions:
    C  A  B
0  10  1  a
1  20  2  b
2  30  3  c
159 chars
12 lines

In the above example, we create a sample dataframe and specify the desired column order using the new_column_order list. We then use the reindex method to reposition the columns according to the specified order. Finally, we print the updated dataframe.

related categories

gistlibby LogSnag