Let’s discuss how to add new columns to existing DataFrame in Pandas. There are multiple ways we can do this task.
Method #1: By declaring a new list as a column.
Note that the length of your list should match the length of the index column otherwise it will show an error.
Method #2: By using DataFrame.insert()
It gives the freedom to add a column at any position we like and not just at the end. It also provides different options for inserting the column values.
Method #3: Using Dataframe.assign() method
This method will create a new dataframe with new column added to the old dataframe.
Method #4: By using a dictionary
We can use a Python dictionary to add a new column in pandas DataFrame. Use an existing column as the key values and their respective values will be the values for new column.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.