subtraction between column a and column b in python in python

Assuming you want to perform column-wise subtraction of two columns in a Pandas DataFrame:

main.py
import pandas as pd

# create sample dataframe
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# perform subtraction of column B from column A
df['C'] = df['A'] - df['B']

# view the resulting dataframe
print(df)

# output:
#    A  B  C
# 0  1  4 -3
# 1  2  5 -3
# 2  3  6 -3

# if you want to perform the operation on a specific subset of columns, you can specify them as a list
df['C'] = df[['A', 'B']].apply(lambda x: x[0] - x[1], axis=1)
447 chars
20 lines

This will create a new column 'C' in the DataFrame which will contain the result of performing subtraction of values in column 'A' from values in column 'B'.

related categories

gistlibby LogSnag