How to add a column to a dataframe in Python

In this article, we will 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.
import pandas as pd # Define a dictionary containing Students data data = {'Name': ['Aby', 'Henry', 'Gowri', 'Riju'], 'Height': [5.1, 6.2, 5.1, 5.2], 'Qualification': ['Bsc', 'BA', 'Bsc', 'Bsc']} # dictionary into DataFrame df = pd.DataFrame(data) # Declare a list that is to be converted into a column address = ['New Delhi', 'Bangalore', 'Chennai', 'Patna'] # Using 'Address' as the column name df['Address'] = address # Observe the result print(df)
Output:
Name Height Qualification Address 0 Aby 5.1 Bsc New Delhi 1 Henry 6.2 BA Bangalore 2 Gowri 5.1 Bsc Chennai 3 Riju 5.2 Bsc Patna
Method 2: By using DataFrame.insert()
import pandas as pd # Define a dictionary containing Students data data = {'Name': ['Aby', 'Henry', 'Gowri', 'Riju'], 'Height': [5.1, 6.2, 5.1, 5.2], 'Qualification': ['Bsc', 'BA', 'Bsc', 'Bsc']} # dictionary into DataFrame df = pd.DataFrame(data) df.insert(2, "Address", ['New Delhi', 'Bangalore', 'Chennai', 'Patna'] ) print(df)
Output:
Name Height Address Qualification 0 Aby 5.1 New Delhi Bsc 1 Henry 6.2 Bangalore BA 2 Gowri 5.1 Chennai Bsc 3 Riju 5.2 Patna Bsc
Subscribe
Login
Please login to comment
0 Discussion