How to make a calculation with a fixed link that changes every day in Pandas?

My data is data on prices for intraday stocks, several days. This is a simplified version:

                     Last                                                   
2015-01-02 08:30:00  2035.00
2015-01-02 10:30:00  2038.25                    
2015-01-02 15:15:00  2025.25  
2015-01-05 08:30:00  2020.25  
2015-01-05 10:30:00  2010.75                      
2015-01-05 15:15:00  2015.00                  
2015-01-06 08:30:00  1988.00 
2015-01-06 10:30:00  1990.25                     
2015-01-06 15:15:00  1970.00

Given that in the data every day the last row is at 15:15:00, how can I make a difference (15:15:00 Row - Last), for each row per day. Here is the desired result.

                     Last      Dif                                             
2015-01-02 08:30:00  2035.25  -10 
2015-01-02 10:30:00  2038.25  -13                  
2015-01-02 15:15:00  2025.25   0
2015-01-05 08:30:00  2020.25  -5.25
2015-01-05 10:30:00  2010.00   5                   
2015-01-05 15:15:00  2015.00   0               
2015-01-06 08:30:00  1988.00  -18
2015-01-06 10:30:00  1990.25  -20.25                    
2015-01-06 15:15:00  1970.00   0
+4
source share
1 answer

You can use both the difference between the last value and the actual value of the string:groupby DatetimeIndex.dayapplyiloc

print df
                        Last
2015-01-02 08:30:00  2035.25
2015-01-02 10:30:00  2038.25
2015-01-02 15:15:00  2025.25
2015-01-05 08:30:00  2020.25
2015-01-05 10:30:00  2010.00
2015-01-05 15:15:00  2015.00
2015-01-06 08:30:00  1988.00
2015-01-06 10:30:00  1990.25
2015-01-06 15:15:00  1970.00

df['Dif'] = df.groupby(df.index.day)['Last'].apply(lambda x: x.iloc[-1] - x)
print df
                        Last    Dif
2015-01-02 08:30:00  2035.25 -10.00
2015-01-02 10:30:00  2038.25 -13.00
2015-01-02 15:15:00  2025.25   0.00
2015-01-05 08:30:00  2020.25  -5.25
2015-01-05 10:30:00  2010.00   5.00
2015-01-05 15:15:00  2015.00   0.00
2015-01-06 08:30:00  1988.00 -18.00
2015-01-06 10:30:00  1990.25 -20.25
2015-01-06 15:15:00  1970.00   0.00
+1
source

All Articles