notageek27
notageek27

Reputation: 101

Using pandas in python compare 2 columns of a row and output a new column if the condition is met

I have the below data frame:

Account Current_Value   Limit   Acc_number
acc1    23              50      8975345
acc2    45              100     7643783
acc3    32              80      7872643
acc4    344             400     9784323
acc5    222             300     3235334
acc6    677             700     6453543

I want to iterate through each of the rows and get the percentage of Current_value over the Limit and if it's above n ( say 95%) I would like to create a new Column Limit_exceeded to Yes/No.

Sample output:

Account Current_Value   Limit   Acc_number  Limit_exceeded
acc1    23              50      8975345     No
acc2    45              100     7643783     No
acc3    78              80      7872643     Yes
acc4    344             400     9784323     No
acc5    222             300     3235334     No
acc6    690             700     6453543     Yes

Upvotes: 1

Views: 27

Answers (1)

Anastasiya-Romanova 秀
Anastasiya-Romanova 秀

Reputation: 3368

One may use numpy.where. Hence

import numpy as np

df['Limit_exceeded'] = np.where(df['Current_Value'] / df['Limit'] > 0.95, 'Yes', 'No')

Alternatively, one may use pandas.Series.map:

df['Limit_exceeded'] = (df['Current_Value'] / df['Limit'] > 0.95).map({True: 'Yes', False: 'No'})

Upvotes: 2

Related Questions