In Python, we can add a column to a pandas DataFrame at a specific location using the DataFrame.insert() function.
import pandas list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] df = pandas.DataFrame(list1, index=["Row 1", "Row 2", "Row 3"], columns=["Column 1", "Column 2", "Column 3"]) print("df before adding column: \n", df) df.insert(1, "New Column", [10, 11, 12]) print("df after adding column: \n", df)
Here, we are first creating a pandas DataFrame df. The DataFrame looks like the following:
Column 1 Column 2 Column 3 Row 1 1 2 3 Row 2 4 5 6 Row 3 7 8 9
Now, we are adding a column after Column 1.
df.insert(1, "New Column", [10, 11, 12])
Please note that the first parameter of insert() indicates the insertion index. The second parameter indicates the label of the column. And the third parameter indicates the values that will be inserted.
So, the output of the above program will be like the following:
df before adding column: Column 1 Column 2 Column 3 Row 1 1 2 3 Row 2 4 5 6 Row 3 7 8 9 df after adding column: Column 1 New Column Column 2 Column 3 Row 1 1 10 2 3 Row 2 4 11 5 6 Row 3 7 12 8 9






0 Comments