compare value in every row of other pandas dataframe

Viewed 121

I have a simple pandas dataframe which has a range column.

map_dict =    { 'range' : [50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 40000, 80000, 120000], 
               'sample' : [1000, 1000, 1000, 1000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000] }

pd.DataFrame.from_dict(map_dict)

I have a value lets say x now I want to compare x at every row in column range e.g. if x> 200 & x< 500 then sum x with the matching value in the column sample.

And another example, if x = 4000, because in this case x> 2000 & x< 5000 in the range column. so matching value in column sample will be 2000, so I will sum with 2000

output:6000

How can I compare a value in other data frame and get the matching value in the next column?

1 Answers

I believe you need subtract values, compare by greater like 0 and get first matched value of sample column:

x = 4000

y = next(iter(df.loc[df['range'].sub(x) > 0, 'sample']))
#alternative for first matched value
#y = df.loc[ y > 0, 'sample'].to_numpy()[0]
print (y)
2000

print (x + y)
6000
Related