how to put a column in a first place pandas dataframe in python

You can use the insert() method to insert a new column at a specific location in a Pandas DataFrame. The syntax of the insert() method is as follows:

main.py
df.insert(loc, column, value, allow_duplicates=False)
54 chars
2 lines
  1. loc: The location where you want to insert the column. This can be an integer index or a column label.
  2. column: The name of the column you want to insert.
  3. value: The actual values you want to insert. This can be a single value to be broadcasted across the entire column or a list of values of the same length as the DataFrame.
  4. allow_duplicates (optional): Whether to allow duplicate column names. The default value is False.

Here's an example:

main.py
import pandas as pd

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

# insert a new column 'D' as the first column
df.insert(0, 'D', [10, 20, 30])

print(df)
207 chars
10 lines

This will output:

main.py
    D  A  B  C
0  10  1  4  7
1  20  2  5  8
2  30  3  6  9
60 chars
5 lines

In this example, we inserted a new column named 'D' at index 0, which means it becomes the first column. We passed a list of three values as the values for the new column.

related categories

gistlibby LogSnag