Skip to content
Advertisement

Dataframe – for each row, compare values of two columns, get value of third column on match

I have a pandas dataframe in Python that contains a list of different stocks by ticker symbol, and for each one, it also records current price and a low and high price alert threshold value.

Below shows a sample of the dataframe:

TICKER CURRENT PRICE($) ALERT PRICE HIGH ($) ALERT PRICE LOW ($)
AMZN 114 180 105
APPL 140 110 190
MSFT 235 340 210

NOTE: I’ve excluded pandas Index column above as this integer can change for the same TICKER stock, depending on the order they randomly get returned in the API request.

For each row in the dataframe, I want to test if the [‘CURRENT PRICE ($)’] is above the [‘ALERT PRICE HIGH ($)’] or below the [‘ALERT PRICE LOW (£)’].

Where the condition if true, I want to pass the ‘TICKER’ ID to a print statement that notifies of the price alert being reached.

In pseudo-code it would be along the lines of the below:

JavaScript

Being fairly new to dataframes, I’m not sure how to translate this into code that will achieve my goal, or if looping over a dataframe in this way is even the best method for this. Hoping someone can help please.

Advertisement

Answer

You can loop over a dataframe but you should use vectorized code whenever possible. In your case, I doubt if either method makes a difference.

Here’s how I would do it:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement