The Wayback Machine - https://web.archive.org/web/20241127234441/https://www.geeksforgeeks.org/create-a-new-column-in-pandas-dataframe-based-on-the-existing-columns/
Open In App

Create a new column in Pandas DataFrame based on the existing columns

Last Updated : 11 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 Dataframe containing data about an event, we would like to create a new column called ‘Discounted_Price’, which is calculated after applying a discount of 10% on the Ticket price.

Example 1: We can use DataFrame.apply() function to achieve this task. 

Python
# importing pandas as pd
import pandas as pd

# Creating the DataFrame
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
                    'Cost':[10000, 5000, 15000, 2000]})

# Print the dataframe
print(df)

Output :

        Date    Event   Cost
0 10/2/2011 Music 10000
1 11/2/2011 Poetry 5000
2 12/2/2011 Theatre 15000
3 13/2/2011 Comedy 2000

 Now we will create a new column called ‘Discounted_Price’ after applying a 10% discount on the existing ‘Cost’ column.

Python
# using apply function to create a new column
df['Discounted_Price'] = df.apply(lambda row: row.Cost - 
                                  (row.Cost * 0.1), axis = 1)

# Print the DataFrame after addition
# of new column
print(df)

Output :

         Date    Event   Cost  Discounted_Price
0 10/2/2011 Music 10000 9000.0
1 11/2/2011 Poetry 5000 4500.0
2 12/2/2011 Theatre 15000 13500.0
3 13/2/2011 Comedy 2000 1800.0

Example 2: We can achieve the same result by directly performing the required operation on the desired column element-wise. 

Python
import pandas as pd

# Creating the DataFrame
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
                    'Cost':[10000, 5000, 15000, 2000]})

# Create a new column 'Discounted_Price' after applying
# 10% discount on the existing 'Cost' column.

# create a new column
df['Discounted_Price'] = df['Cost'] - (0.1 * df['Cost'])

# Print the DataFrame after 
# addition of new column
print(df)

Output :

        Date    Event   Cost  Discounted_Price
0 10/2/2011 Music 10000 9000.0
1 11/2/2011 Poetry 5000 4500.0
2 12/2/2011 Theatre 15000 13500.0
3 13/2/2011 Comedy 2000 1800.0

Example 3: Using DataFrame.map() function to create new column from existing column using a mapping function

We will create a dataframe with some sample data:

Python
data = {
    "name": ["John", "Ted", "Dev", "Brad", "Rex", "Smith", "Samuel", "David"],
    "salary": [10000, 20000, 50000, 45500, 19800, 95000, 5000, 50000]
}
# create dataframe from data dictionary
df = pd.DataFrame(data)
# print the dataframe
display(df.head())

Output:

    name    salary
0 John 10000
1 Ted 20000
2 Dev 50000
3 Brad 45500
4 Rex 19800

Now, we will create a mapping function (salary_stats) and use the DataFrame.map() function to create a new column from an existing column

Python
def salary_stats(value):
    if value < 10000:
        return "very low"
    if 10000 <= value < 25000:
        return "low"
    elif 25000 <= value < 40000:
        return "average"
    elif 40000 <= value < 50000:
        return "better"
    elif value >= 50000:
        return "very good"

df['salary_stats'] = df['salary'].map(salary_stats)
display(df.head())

Output:

name    salary    salary_stats
0 John 10000 low
1 Ted 20000 low
2 Dev 50000 very good
3 Brad 45500 better
4 Rex 19800 low

Explanation: Here we have used pandas DataFrame.map() function to map each value to a string based on our defined mapping logic. The resultant series of values is assigned to a new column, “salary_stats”.\

Create a new column in Pandas DataFrame based on the existing columns – FAQs

How to create a new column in pandas based on an existing column?

To create a new column in a pandas DataFrame based on an existing column, simply apply operations directly to the column:

import pandas as pd

df = pd.DataFrame({
'A': [10, 20, 30, 40]
})

# Create a new column 'B' that is twice the value of 'A'
df['B'] = df['A'] * 2
print(df)

How to create a new column in pandas DataFrame based on condition?

To create a new column based on conditions applied to other columns, use the np.where() function from the numpy library, or direct pandas operations:

import numpy as np

# Create a new column based on condition
df['C'] = np.where(df['A'] > 20, 'High', 'Low')
print(df)

How to create a new DataFrame from existing DataFrame with selected columns?

To create a new DataFrame from selected columns of an existing DataFrame, simply specify the columns you want to include:

# Creating a new DataFrame with selected columns
new_df = df[['A', 'B']]
print(new_df)

How to create a DataFrame with different columns?

To create a DataFrame with different columns, you can specify the data and column names when initializing the DataFrame:

# Creating a DataFrame with specific columns
new_df = pd.DataFrame({
'Column1': [1, 2, 3],
'Column2': ['A', 'B', 'C'],
'Column3': [True, False, True]
})
print(new_df)

How to create a DataFrame with multiple columns?

Creating a DataFrame with multiple columns involves specifying each column and its values in the DataFrame constructor:

# Initialize a DataFrame with multiple columns
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Gender': ['Female', 'Male', 'Male']
})
print(df)


Previous Article
Next Article

Similar Reads

Adding New Column to Existing DataFrame in Pandas
Let's discuss how to add new columns to the existing DataFrame in Pandas. There can be multiple methods to add new column or multiple columns to existing dataframe, based on different requirement. By Declaring a new List as column Let's first create a dataframe. We will keep using this dataframe for all examples in this article. [GFGTABS] Python im
6 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
4 min read
How to Fix an "Error When Adding a New Row to My Existing DataFrame in Pandas"
Pandas is a powerful and widely-used library in Python for data manipulation and analysis. One common task when working with data is adding new rows to an existing DataFrame. However, users often encounter errors during this process. This article will explore common errors that arise when adding new rows to a DataFrame and provide solutions to fix
6 min read
Create MapType Column from Existing Columns in PySpark
An RDD transformation that applies the transformation function to every element of the data frame is known as a map in Pyspark. There occurs various situations when you have numerous columns and you need to convert them to map-type columns. It can be done easily by using the create_map function with the map key column name and column name as argume
3 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
PySpark dataframe add column based on other columns
In this article, we are going to see how to add columns based on another column to the Pyspark Dataframe. Creating Dataframe for demonstration: Here we are going to create a dataframe from a list of the given dataset. C/C++ Code # Create a spark session from pyspark.sql import SparkSession spark = SparkSession.builder.appName('SparkExamples').getOr
2 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
Split a text column into two columns in Pandas DataFrame
Let's see how to split a text column into two columns in Pandas DataFrame. Method #1 : Using Series.str.split() functions. Split Name column into two different columns. By default splitting is done on the basis of single space by str.split() function. # import Pandas as pd import pandas as pd # create a new data frame df = pd.DataFrame({'Name': ['J
3 min read
Select all columns, except one given column in a Pandas DataFrame
DataFrame Data structure are the heart of Pandas library. DataFrames are basically two dimension Series object. They have rows and columns with rows representing the index and columns representing the content. Now, let's see how to Select all columns, except one given column in Pandas DataFrame in Python. Creating a DataFrame: C/C++ Code # import p
2 min read
Sort rows or columns in Pandas Dataframe based on values
In this article, Let's discuss how to Sort rows or columns in Pandas Dataframe based on values. Pandas sort_values() method sorts a data frame in Ascending or Descending order of passed Column. It's different than the sorted Python function since it cannot sort a data frame and particular column cannot be selected. Syntax: DataFrame.sort_values(by,
7 min read
Split dataframe in Pandas based on values in multiple columns
In this article, we are going to see how to divide a dataframe by various methods and based on various parameters using Python. To divide a dataframe into two or more separate dataframes based on the values present in the column we first create a data frame. Creating a DataFrame for demonestration C/C++ Code # importing pandas as pd import pandas a
3 min read
Delete duplicates in a Pandas Dataframe based on two columns
A dataframe is a two-dimensional, size-mutable tabular data structure with labeled axes (rows and columns). It can contain duplicate entries and to delete them there are several ways. The dataframe contains duplicate values in column order_id and customer_id. Below are the methods to remove duplicate values from a dataframe based on two columns. Me
2 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
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
Get column index from column name of a given Pandas DataFrame
Let's learn how to get the index of a column based on its name using the DataFrame.columns attribute and Index.get_loc() method from the pandas library. Index.get_loc() Method Index.get_loc() function finds the index of a specified column name and returns an integer if the column name is unique. Syntax: Index.get_loc(key, method=None, tolerance=Non
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
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
How to Sort a Pandas DataFrame based on column names or row index?
Pandas dataframe.sort_index() method sorts objects by labels along the given axis. Basically, the sorting algorithm is applied to the axis labels rather than the actual data in the Dataframe and based on that the data is rearranged. Creating Pandas Dataframe Create a DataFrame object from the Python list of tuples with columns and indices, say colu
3 min read
Python | Creating a Pandas dataframe column based on a given condition
While operating on data, there could be instances where we would like to add a column based on some condition. There does not exist any library function to achieve this task directly, so we are going to see how we can achieve this goal. In this article, we will see how to create a Pandas dataframe column based on a given condition in Python. Proble
8 min read
Append list of dictionary and series to a existing Pandas DataFrame in Python
In this article, we will discuss how values from a list of dictionaries or Pandas Series can be appended to an already existing pandas dataframe. For this purpose append() function of pandas, the module is sufficient. Syntax: DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None) Parameters :other : DataFrame or Series/dict-
2 min read
How to insert a pandas DataFrame to an existing PostgreSQL table?
In this article, we are going to see how to insert a pandas DataFrame to an existing PostgreSQL table. Modules neededpandas: Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fas
3 min read
How to Append Pandas DataFrame to Existing CSV File?
In this discussion, we'll explore the process of appending a Pandas DataFrame to an existing CSV file using Python. Add Pandas DataFrame to an Existing CSV File. To achieve this, we can utilize the to_csv() function in Pandas with the 'a' parameter to write the DataFrame to the CSV file in append mode. Pandas DataFrame to_csv() Syntax Syntax : df.t
3 min read
How to add one row in an existing Pandas DataFrame?
Adding rows to a Pandas DataFrame is a common task in data manipulation. Here are the primary methods to add rows to a DataFrame, along with their syntax and examples in Pandas. Add Row to Pandas Dataframe # Append the new row to the DataFramenew_row = {'Name': 'Amy', 'Maths': 89, 'Science': 93}df = df.append(new_row, ignore_index=True)Table of Con
4 min read
Create new column with function in Spark Dataframe
In this article, we are going to learn how to create a new column with a function in the PySpark data frame in Python. PySpark is a popular Python library for distributed data processing that provides high-level APIs for working with big data. The data frame class is a key component of PySpark, as it allows you to manipulate tabular data with distr
3 min read
Create a DataFrame from a Numpy array and specify the index column and column headers
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame. Approach : Import the Pandas and Numpy modules. Create a Numpy array. Create list of index values and column values for the DataFrame. Create the DataFrame. Display the DataFrame. Example 1 : # importiong the
2 min read
Create a column using for loop in Pandas Dataframe
Adding a new column in an already created dataframe is quite easy. Adding a new column is actually required to process the data of dataframe created earlier. For that purpose, we can process the existing data and make a separate column to store the data. The simplest way to add a new column along with data is by creating a new column and assigning
3 min read
Add New Columns to Polars DataFrame
Polars is a fast DataFrame library implemented in Rust and designed to process large datasets efficiently. It is gaining popularity as an alternative to pandas, especially when working with large datasets or needing higher performance. One common task when working with DataFrames is adding new columns, which can be done easily in Polars. In this ar
3 min read
Python Psycopg2 - Concatenate columns to new column
In this article, we are going to see how to concatenate multiple columns of a table in a PostgreSQL database into one column. To concatenate two or more columns into one, PostgreSQL provides us with the concat() function. Table for demonstration: In the below code, first, a connection is formed to the PostgreSQL database 'geeks' by using the connec
2 min read
Sum of two columns in openpyxl and result in a new column
Most of the developers especially developers who work in the field of data use Excel alongside other programming languages on a daily basis. Now Sometimes a situation might arise that they need to find the sum of two adjacent or non-adjacent columns and fill a separate column using the summation of each row. In this article, we will see how we can
4 min read
Split single column into multiple columns in PySpark DataFrame
pyspark.sql.functions provide a function split() which is used to split DataFrame string Column into multiple columns. Syntax: pyspark.sql.functions.split(str, pattern, limit=- 1) Parameters: str: str is a Column or str to split.pattern: It is a str parameter, a string that represents a regular expression. This should be a Java regular expression.l
4 min read
three90RightbarBannerImg