JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Subtracting Two Columns in Pandas DataFrame

Author:JIYIK Last Updated:2025/05/01 Views:

Pandas can handle very large data sets and has a variety of functions and operations that can be applied to the data.

One of the simple operations is to subtract two columns and store the result in a new column, which we will discuss in this tutorial. This simple task can be done in many ways. We will calculate the difference between the 'a'and columns in the following DataFrame.'d'

import pandas as pd

df = pd.DataFrame(
    [[10, 6, 7, 8], [1, 9, 12, 14], [5, 8, 10, 6]], columns=["a", "b", "c", "d"]
)

print(df)

Output:

    a  b   c   d
0  10  6   7   8
1   1  9  12  14
2   5  8  10   6

Subtracting two columns in Pandas using __getitem__syntax ( )[]

The simplest way to subtract two columns is to access the desired column and create a new column using __getitem__the syntax ( ). For example:[]

import pandas as pd

df = pd.DataFrame(
    [[10, 6, 7, 8], [1, 9, 12, 14], [5, 8, 10, 6]], columns=["a", "b", "c", "d"]
)

df["d - a"] = df["d"] - df["a"]

print(df)

Output:

    a  b   c   d  d - a
0  10  6   7   8     -2
1   1  9  12  14     13
2   5  8  10   6      1

Subtracting Two Columns Using Functions in Pandas

We can easily create a function in Pandas to subtract two columns and apply()apply it to the specified columns of the DataFrame using the function. We will apply()provide the function with the argument axisand set it to 1, indicating that the function is applied to the column.

import pandas as pd

df = pd.DataFrame(
    [[10, 6, 7, 8], [1, 9, 12, 14], [5, 8, 10, 6]], columns=["a", "b", "c", "d"]
)


def x(a, b):
    return a - b


df["d - a"] = df.apply(lambda f: x(f["d"], f["a"]), axis=1)

print(df)

Output:

    a  b   c   d  d - a
0  10  6   7   8     -2
1   1  9  12  14     13
2   5  8  10   6      1

Since column subtraction is a relatively simple operation, we can directly use lambdathe keyword apply()to create a simple one-line function in the function.

import pandas as pd

df = pd.DataFrame(
    [[10, 6, 7, 8], [1, 9, 12, 14], [5, 8, 10, 6]], columns=["a", "b", "c", "d"]
)

df["d - a"] = df.apply(lambda x: x["d"] - x["a"], axis=1)

print(df)

Output:

    a  b   c   d  d - a
0  10  6   7   8     -2
1   1  9  12  14     13
2   5  8  10   6      1

assign()Subtracting two columns in Pandas using the

The DataFrame assign()method is used to add a column to a DataFrame after performing some operation. It returns a new DataFrame containing all the original and new columns. The following example will show how to assign()subtract two columns using the method.

import pandas as pd

df = pd.DataFrame(
    [[10, 6, 7, 8], [1, 9, 12, 14], [5, 8, 10, 6]], columns=["a", "b", "c", "d"]
)

df = df.assign(d_minus_a=df["d"] - df["a"])

print(df)

Output:

    a  b   c   d  d_minus_a
0  10  6   7   8         -2
1   1  9  12  14         13
2   5  8  10   6          1

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Dropping columns by index in Pandas DataFrame

Publish Date:2025/05/01 Views:99 Category:Python

DataFrames can be very large and can contain hundreds of rows and columns. It is necessary to master the basic maintenance operations of DataFrames, such as deleting multiple columns. We can use dataframe.drop() the method to delete columns

Pandas Copy DataFrame

Publish Date:2025/05/01 Views:53 Category:Python

This tutorial will show you how to DataFrame.copy() copy a DataFrame object using the copy method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 ], "Cost" : [ "300" , "400" , "350" ], } ) print (items_df) Output:

Pandas DataFrame.ix[] Function

Publish Date:2025/05/01 Views:168 Category:Python

Python Pandas DataFrame.ix[] function slices rows or columns based on the value of the argument. pandas.DataFrame.ix[] grammar DataFrame . ix[index = None , label = None ] parameter index Integer or list of integers used to slice row indice

Pandas DataFrame.describe() Function

Publish Date:2025/05/01 Views:120 Category:Python

Python Pandas DataFrame.describe() function returns the statistics of a DataFrame. pandas.DataFrame.describe() grammar DataFrame . describe( percentiles = None , include = None , exclude = None , datetime_is_numeric = False ) parameter perc

Pandas DataFrame.astype() Function

Publish Date:2025/05/01 Views:160 Category:Python

Python Pandas DataFrame.astype() function changes the data type of an object to the specified data type. pandas.DataFrame.astype() grammar DataFrame . astype(dtype, copy = True , errors = "raise" ) parameter dtype The data type we want to a

Pandas DataFrame.to_dict() Function

Publish Date:2025/05/01 Views:188 Category:Python

Python Pandas DataFrame.to_dict() function converts the given DataFrame to a dictionary. pandas.DataFrame.to_dict() Syntax DataFrame . to_dict(orient = 'dict' , into = class ' dict ' ) parameter orient This parameter determines the type of

Pandas DataFrame.reset_index() Function

Publish Date:2025/05/01 Views:140 Category:Python

Python Pandas DataFrame.reset_index() function resets the index of the given DataFrame. It replaces the old index with the default index. If the given DataFrame has a MultiIndex, then this method removes all the levels. pandas.DataFrame.rep

Pandas DataFrame.resample() Function

Publish Date:2025/05/01 Views:78 Category:Python

Python Pandas DataFrame.resample() function resamples time series data. pandas.DataFrame.resample() Syntax DataFrame . resample( rule, axis = 0 , closed = None , label = None , convention = "start" , kind = None , loffset = None , base = No

Pandas DataFrame.insert() Function

Publish Date:2025/05/01 Views:116 Category:Python

Python Pandas DataFrame.insert() function inserts a column at the specified position into the DataFrame. pandas.DataFrame.insert() Syntax DataFrame . insert(loc, column, value, allow_duplicates = False ) parameter loc It is an integer param

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial