how to move column to the first position in pandas in python

To move a column to the first position in a DataFrame using pandas in Python, you can use the following steps:

  1. Get a list of all the column names in the DataFrame.
  2. Remove the column you want to move from the list.
  3. Insert the column at the beginning of the list.
  4. Reorder the columns in the DataFrame using the updated list.

Here's an example code snippet that demonstrates these steps:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3],
        'B': [4, 5, 6],
        'C': [7, 8, 9]}
df = pd.DataFrame(data)

# Get the column names
columns = df.columns.tolist()

# Remove the column you want to move and insert it at the beginning
columns.insert(0, 'C')
columns.remove('C')

# Reorder the columns in the DataFrame
df = df[columns]

# Print the resulting DataFrame
print(df)
411 chars
21 lines

Output:

main.py
   C  A  B
0  7  1  4
1  8  2  5
2  9  3  6
44 chars
5 lines

In the above example, we move the column 'C' to the first position in the DataFrame by reordering the column names and then reassigning the DataFrame with the updated order of columns.

related categories

gistlibby LogSnag