Make new column in Pandas DataFrame by adding values from other columns

Given a Pandas DataFrame, we have to make new column by adding values from other columns. By Pranit Sharma Last updated : September 25, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Given a DataFrame, we need to create a new column that contains the value which is generated by performing some operation between the other column values.

Creating new column in Pandas DataFrame by adding values from other columns

To create a new column in pandas DataFrame which contains the value generated by performing some operation on the values of other columns, we will first create a DataFrame, the dataframe will contain 2 columns initially and we will perform a row-wise product of both columns and store all the values in a list. Finally, we will assign this list to a new column of the DataFrame.

Let us understand with the help of an example,

Python program to make new column in Pandas DataFrame by adding values from other columns

# Importing pandas package
import pandas as pd

# Creating a Dictionary
d = {
    'Marks_Obtained':[446,473,410,420],
    'Total_Marks': [500,500,500,500]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Creating a list of values
l = []
for i in range(len(df['Marks_Obtained'])):
    a = (df['Marks_Obtained'][i]/df['Total_Marks'][i])*100
    l.append(str(a)+'%')

# Creating a new column and assigning its values 
# as the list defined above
df['Percentage'] = l

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Make new column in Pandas DataFrame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.