How to subtract a single value from column of pandas DataFrame?

Given a pandas dataframe, we have to subtract a single value from column.
Submitted by Pranit Sharma, on December 12, 2022

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

Let us suppose that we are given the Pandas data frame with multiple columns containing numerical values.

We have a value (say 7) that we want to subtract from each member of a particular column. The resulting dataframe would contain the same column but with values that are 7 less than the previous values.

Subtracting a single value from column of pandas DataFrame

For this purpose, we will simply use the square brackets to access that particular column and modify this column by subtracting 7 from each value of this column.

Let us understand with the help of an example,

Python program to subtract a single value from column of pandas DataFrame

# Importing pandas
import pandas as pd

# Import numpy
import numpy as np

# Creating a dataframe
df = pd.DataFrame({
    'A':[50244,6042343,70234,4245],
    'B':[34534,5356,56445,1423],
    'C':[46742,685,4563,7563]
})

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

# Subtracting 7 from column B
df['B'] = df['B']-7

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

Output

The output of the above program is:

Example: How to subtract a single value from column of pandas DataFrame?frame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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