How to add a new column to an existing DataFrame?

 

You can add a new column to an existing DataFrame in Python using the Pandas library. Here's how to do it with an example:

python
import pandas as pd # Create a sample DataFrame data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]} df = pd.DataFrame(data) # Add a new column to the DataFrame df['City'] = ['New York', 'Los Angeles', 'Chicago'] # Print the updated DataFrame print(df)

In this example:

  1. We import the Pandas library using import pandas as pd.

  2. We create a sample DataFrame df with two columns: 'Name' and 'Age'.

  3. To add a new column 'City' to the DataFrame, we simply assign a list of values to df['City']. The length of the list should match the number of rows in the DataFrame.

  4. We print the updated DataFrame, and it will now have three columns: 'Name', 'Age', and 'City'.

The output of the code will be:

markdown
Name Age City 0 Alice 25 New York 1 Bob 30 Los Angeles 2 Charlie 35 Chicago

You can add new columns with various data types, including strings, numbers, or even computed values based on existing columns. Just make sure the length of the list or Series you assign to the new column matches the number of rows in the DataFrame.

Comments