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.py54 chars2 lines
loc
: The location where you want to insert the column. This can be an integer index or a column label.column
: The name of the column you want to insert.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.allow_duplicates
(optional): Whether to allow duplicate column names. The default value is False
.Here's an example:
main.py207 chars10 lines
This will output:
main.py60 chars5 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.
gistlibby LogSnag