The Wayback Machine - https://web.archive.org/web/20250304095328/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
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)

Level up your coding with DSA Python in 90 days! Master key algorithms, solve complex problems, and prepare for top tech interviews. Join the Three 90 Challenge—complete 90% of the course in 90 days and earn a 90% refund. Start your Python DSA journey today!


Next Article

Similar Reads

Adding New Column to Existing DataFrame in Pandas
Adding a new column to a DataFrame in Pandas is a simple and common operation when working with data in Python. You can quickly create new columns by directly assigning values to them. Let's discuss how to add new columns to the existing DataFrame in Pandas. There can be multiple methods, based on different requirement. Adding New Column to Existin
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 ones
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
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
2 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. Python3 # Create a spark session from pyspark.sql import SparkSession spark = SparkSession.builder.appName('SparkExamples').getOrCre
2 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. Python3 # import Pandas as pd import pandas as pd # create a new data frame df = pd.DataFrame({'Na
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:Python3 # import panda
2 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 demonestrationPython3 # importing pandas as pd import pandas as pd
3 min read