0

Hi I had created a dataframe with Acutal Close, High, Low and now I will have to calculate the Day-Change, 3Days-Change, 2weeks-Change for each of the row. With the code below, I can see the Day-Change field with Blank/NaN value (10/27/2009 D-Chg field), and now how can I get python to Auto-Pick the last trading date (10/23/2009) AC price for calculation when shifted date doesn't exist?

data["D-Chg"]=stock_store['Adj Close'] - stock_store['Adj Close'].shift(1, freq='B')

enter image description here

Thanks with Regards

user125104
  • 29
  • 1
  • 6
  • For me it's not really clear what you try to do, what you already have and what the problem is with what you already have... – po.pe Jun 25 '21 at 13:55

1 Answers1

0

format your first column to datetime.

data['Mycol'] =  pd.to_datetime(data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

get the max value.

last_date = data['date'].max()

Get the most up-to-date row

is_last = data['date'] == last_date
data[is_last]

This may be done in one step if you give your desired column to max().

Florian Fasmeyer
  • 795
  • 5
  • 18
  • Under "data['Mycol'] = pd.to_datetime(data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')", i'm getting error - KeyError: 'Date'. I'm currently using data['Date'] as Index. – user125104 Jun 25 '21 at 15:33
  • Then you can use the Index instead of a column. df.index.max(). If you need to make your index a datetime : df.index = pd.to_datetime(df.index) – Florian Fasmeyer Jun 25 '21 at 16:20
  • Thanks Florian, would it be possibile to have 1 statement with if....else to check the index(date) shift1 is = 'NaN' then it will pick Max Index (Date)\Adj Close value? data["D-Chg"]=stock_store['Adj Close'] - if stock_store['Adj Close'].shift(1, freq='B')='NaN'...... – user125104 Jun 28 '21 at 07:16