Pandas dataframe create new columns and fill with calculated values from same dataframe

Given a pandas dataframe, we have to create new columns and fill with calculated values from same dataframe. By Pranit Sharma Last updated : October 03, 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

We are given a DataFrame with 3 columns A, B, and C, and all of these columns contain integer values. We need to create some new columns, for example, the sum column which contains the row-wise sum. Percentage of column A, percentage of column B, and same for C.

Creating new columns and fill with calculated values from same dataframe

We will create these new columns and also calculate the sum and individual percentage of each column and store these values in the new columns. Consider the below-given code statements to achieve this task,

# Creating sum column
df['sum']  = df.sum(axis=1)

# Creating percentage column
df['A_perc'] = df['A']/df['sum']
df['B_perc'] = df['B']/df['sum']
df['C_perc'] = df['C']/df['sum']

Let us understand with the help of an example,

Python program to create new columns and fill with calculated values from same dataframe

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'A':[32,21,19,23],
    'B':[27,40,30,24],
    'C':[20,21,21,20]
}

# Creating DataFrame
df = pd.DataFrame(d)

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

# Creating sum column
df['sum']  = df.sum(axis=1)

# Creating percentage column
df['A_perc'] = df['A']/df['sum']

df['B_perc'] = df['B']/df['sum']

df['C_perc'] = df['C']/df['sum']

# Display Result
print("Result:\n",df)

Output

The output of the above program is:

Example: Create new columns and fill with calculated values from same dataframe

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






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