Home > Software design >  Pull last 3 elements from a DataFrame as an array of numbers
Pull last 3 elements from a DataFrame as an array of numbers

Time:12-10

I have a DataFrame where the columns are open, high, low, close, volume (stock data). And the rows are the last 10 trading days (stock symbol & date)

I need to get the most recent three close values in an array. And I'm sure this can be done, but I can't figure out how. I know the values are history.close[-1], history.close[-2], history.close[-3].

How do I pull this end slice as an array of numbers?

CodePudding user response:

Try using a negative array index and slice notation. This is one of the really nice features of python:

tail = history.close[-3:]

or, if you need them as a numpy array:

tail_arr = history.close.values[-3:]

CodePudding user response:

You could simply do

history["close"].tail(3).to_array()
  • Related