Iterating through columns and subtracting with the Last Column in pd.dataframe

Learn, how to iterate through columns and subtracting with the Last Column in pd.dataframe? By Pranit Sharma Last updated : October 06, 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

Suppose we are given a dataframe with some columns (say a, b, c, d) and we need to iterate through this dataframe and subtract these columns from the last column of the dataframe.

Iterating through columns and subtracting with the Last Column

For this purpose, we will use the drop() method to get rid of the no target columns, then rsub() will help us to subtract the data. Finally, we will concat to the original data.

Let us understand with the help of an example,

Python program to iterate through columns and subtracting with the Last Column in pd.dataframe

# Import numpy
import numpy as np

# Import pandas
import pandas as pd

# Creating a dataframe
df = pd.DataFrame({'a':[1,2,3,4],'b':[2,3,4,5],'c':[6,7,8,9],'d':[10,11,12,13]})

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

# Subtracting a column from last column
res = df.drop(columns=['a', 'd']).rsub(df['d'] ,axis=0)

# Concatenating data
res = pd.concat([df.assign(**res), res.sum().to_frame().T])

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

Output

The output of the above program is:

Example: Iterating through columns and subtracting with the Last Column in pd.dataframeframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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