0

I have the following dataframe, and a variable equal to 20. I need to find where this variable is in col2 (here between 10 and 50) and output the lowest value in col1, here would be 2. Another example would be to have a variable equal to 51 and the correct output of col1 would be 3.

I could do it with an if formula but I am hopping for a better solution for larger datasets.

d = {'col1': [1, 2, 3, 4, 5], 'col2': [0, 10, 50, 60, 70]}
df = pd.DataFrame(data=d)

enter image description here

0

1 Answer 1

1

Use boolean indexing with DataFrame.loc and then get last value of column col1 by Series.iat:

a = df.loc[df['col2'] <= 20, 'col1'].iat[-1]
print (a)
2
a = df.loc[df['col2'] <= 51, 'col1'].iat[-1]
print (a)
3
a = df.loc[df['col2'] <= 10, 'col1'].iat[-1]
print (a)
2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.