The Wayback Machine - https://web.archive.org/web/20240609151331/https://www.geeksforgeeks.org/adding-new-column-to-existing-dataframe-in-pandas/
Open In App

Adding new column to existing DataFrame in Pandas

Last Updated : 21 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Adding new columns to an existing DataFrame is a fundamental task in data analysis using Pandas. It allows you to enrich your data with additional information and facilitate further analysis and manipulation. This article will explore various methods for adding new columns, including simple assignment, the insert() method, the assign() method. Let’s discuss adding new columns to Pandas’s existing DataFrame.

What is Pandas DataFrame?

A Pandas DataFrame is a two-dimensional, size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). It’s a fundamental data structure in the Python data science ecosystem and provides a powerful way to work with tabular data.

Here are some key features of a Pandas DataFrame:

  • Data representation: Stores data in a table format with rows and columns.
  • Heterogeneous data types: Can hold different data types in different columns (e.g., integers, floats, strings, booleans).
  • Labeling: Each row and column has a label (index and column names).
  • Mutable: Allows data manipulation and modification.
  • Powerful operations: Provides various functions and methods for data analysis, manipulation, and exploration.
  • Extensible: Can be customized and extended with additional functionalities through libraries and user-defined functions.

Adding a new Column to Existing DataFrame in Pandas in Python

There are multiple ways to add a new Column to an Existing DataFrame in Pandas in Python:

Creating a Sample Dataframe

Here we are creating a Sample Dataframe:

Python3




import pandas as pd
 
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Height': [5.1, 6.2, 5.1, 5.2],
        'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
 
df = pd.DataFrame(data)
print(df)


Output:

 Name  Height Qualification
0     Jai     5.1           Msc
1  Princi     6.2            MA
2  Gaurav     5.1           Msc
3    Anuj     5.2           Msc

Note that the length of your list should match the length of the index column otherwise it will show an error. 

Add a New Column to an Existing Datframe 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.

Python3




import pandas as pd
 
# Define a dictionary containing Students data
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Height': [5.1, 6.2, 5.1, 5.2],
        'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Using DataFrame.insert() to add a column
df.insert(2, "Age", [21, 23, 24, 21], True)
 
# Observe the result
print(df)


Output: 

Name  Height  Age Qualification
0     Jai     5.1   21           Msc
1  Princi     6.2   23            MA
2  Gaurav     5.1   24           Msc
3    Anuj     5.2   21           Msc

Adding Columns to Pandas DataFrame using Dataframe.assign()

This method will create a new dataframe with a new column added to the old dataframe.

Python3




import pandas as pd
 
# Define a dictionary containing Students data
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Height': [5.1, 6.2, 5.1, 5.2],
        'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
 
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Using 'Address' as the column name and equating it to the list
df2 = df.assign(address=['Delhi', 'Bangalore', 'Chennai', 'Patna'])
 
print(df2)


Output: 

 Name  Height Qualification    address
0     Jai     5.1           Msc      Delhi
1  Princi     6.2            MA  Bangalore
2  Gaurav     5.1           Msc    Chennai
3    Anuj     5.2           Msc      Patna

Pandas Add Column to DataFrame 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 a new column.

Python3




# Import pandas package
import pandas as pd
 
# Define a dictionary containing Students data
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Height': [5.1, 6.2, 5.1, 5.2],
        'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
 
# Define a dictionary with key values of
# an existing column and their respective
# value pairs as the # values for our new column.
address = {'Delhi': 'Jai', 'Bangalore': 'Princi',
           'Patna': 'Gaurav', 'Chennai': 'Anuj'}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
 
# Provide 'Address' as the column name
df['Address'] = address
 
# Observe the output
print(df)


Output: 

Name  Height Qualification    Address
0     Jai     5.1           Msc      Delhi
1  Princi     6.2            MA  Bangalore
2  Gaurav     5.1           Msc    Chennai
3    Anuj     5.2           Msc      Patna

Adding a New Column to a Pandas DataFrame using List

In this example, Pandas add new columns from list “Address” to an existing Pandas DataFrame using a dictionary and a list.

Python3




# Declare a list that is to be converted into a column
address = ['Delhi', 'Bangalore', 'Chennai', 'Patna']
 
# Using 'Address' as the column name
# and equating it to the list
df['Address'] = address
 
print(df)


Output: 

Name  Height Qualification    Address
0     Jai     5.1           Msc      Delhi
1  Princi     6.2            MA  Bangalore
2  Gaurav     5.1           Msc    Chennai
3    Anuj     5.2           Msc      Patna

Add A New Column To An Existing Pandas DataFrame using Dataframe.loc()

In this example, It creates a Pandas DataFrame named df with columns “Name”, “Height”, and “Qualification” and adds a new column “Address” using the loc attribute.

Python3




import pandas as pd
 
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
       'Height': [5.1, 6.2, 5.1, 5.2],
       'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
 
df = pd.DataFrame(data)
 
# Create the list of new column values
address = ["Delhi", "Bangalore", "Chennai", "Patna"]
 
# Add the new column using loc
df.loc[:, "Address"] = address
 
print(df)


Output:

Name  Height Qualification    Address
0     Jai     5.1           Msc      Delhi
1  Princi     6.2            MA  Bangalore
2  Gaurav     5.1           Msc    Chennai
3    Anuj     5.2           Msc      Patna

Adding More than One columns in Existing Dataframe 

In this example, it expands an existing Pandas DataFrame df with two new columns, “Age” and “State”, using their respective data lists.

Python3




import pandas as pd
 
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
        'Height': [5.1, 6.2, 5.1, 5.2],
        'Qualification': ['Msc', 'MA', 'Msc', 'Msc'],
        'Address': ['Delhi', 'Bangalore', 'Chennai', 'Patna']}
 
df = pd.DataFrame(data)
 
# Define new data for additional columns
age = [22, 25, 23, 24]
state = ['NCT', 'Karnataka', 'Tamil Nadu', 'Bihar']
 
# Add multiple columns using dictionary assignment
new_data = {'Age': age, 'State': state }
df = df.assign(**new_data)
 
print(df)


Output:

    Name  Height Qualification    Address  Age       State
0     Jai     5.1           Msc      Delhi   22         NCT
1  Princi     6.2            MA  Bangalore   25   Karnataka
2  Gaurav     5.1           Msc    Chennai   23  Tamil Nadu
3    Anuj     5.2           Msc      Patna   24       Bihar

Conclusion

Understanding how to add new columns to DataFrames is essential for data exploration and manipulation in Pandas. Choosing the appropriate method depends on the specific context and desired outcome. By mastering these techniques, you can effectively manipulate, analyze, and gain valuable insights from your data.



Previous Article
Next Article

Similar Reads

Create a new column in Pandas DataFrame based on the existing columns
While working with data in Pandas, we perform a vast array of operations on the data to get the data in the desired form. One of these operations could be that we want to create new columns in the DataFrame based on the result of some operations on the existing columns in the DataFrame. Let's discuss several ways in which we can do that. Given a Da
3 min read
Adding new enum column to an existing MySQL table using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to add a new enum column to an existing MySQL table using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python
1 min read
Adding New Variable to Pandas DataFrame
In this article let's learn how to add a new variable to pandas DataFrame using the assign() function and square brackets. Pandas is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Whereas Pandas DataFrame is a pot
3 min read
How to add column sum as new column in PySpark dataframe ?
In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let's discuss the various methods how we add sum as new columns But first, let's create Dataframe for Demonstratio
4 min read
Adding two columns to existing PySpark DataFrame using withColumn
In this article, we are going to see how to add two columns to the existing Pyspark Dataframe using WithColumns. WithColumns is used to change the value, convert the datatype of an existing column, create a new column, and many more. Syntax: df.withColumn(colName, col) Returns: A new :class:`DataFrame` by adding a column or replacing the existing c
2 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
2 min read
Inserting data into a new column of an already existing table in MySQL using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to Inserting data into a new column of an already existing table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector Python modul
2 min read
Get column index from column name of a given Pandas DataFrame
In this article we will see how to get column index from column name of a Dataframe. We will use Dataframe.columns attribute and Index.get_loc method of pandas module together. Syntax: DataFrame.columns Return: column names index Syntax: Index.get_loc(key, method=None, tolerance=None) Return: loc : int if unique index, slice if monotonic index, els
2 min read
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read