Home > Back-end >  Retrieve last row of a data frame with condition
Retrieve last row of a data frame with condition

Time:03-08

I have a data frame (df) as

                                   Open          High           Low         Close      Volume  Dividends  Stock Splits
Datetime                                                                                                          
2022-03-08 09:55:00 05:30  15829.900391  15832.049805  15819.950195  15831.750000           0          0             0
2022-03-08 09:56:00 05:30  15830.750000  15839.349609  15818.599609  15838.150391           0          0             0
2022-03-08 09:57:00 05:30  15838.150391  15838.250000  15830.150391  15830.750000           0          0             0
2022-03-08 09:58:01 05:30  15830.400391  15830.400391  15830.400391  15830.400391           0          0             0

if I will print df.tail(1), it will print

2022-03-08 09:58:01 05:30  15830.400391  15830.400391  15830.400391  15830.400391           0          0             0

But, I want to print the last row which has "00" seconds. For example, in this case, it should retrieve last row as "09:57:00" . Output should be :

2022-03-08 09:57:00 05:30  15838.150391  15838.250000  15830.150391  15830.750000           0          0             0

How can I achieve it?

CodePudding user response:

You can filter the index first

#df.index = pd.to_datetime(df.index)

out = df[df.index.second==0].tail(1)
Out[644]: 
                                     Open          High  ...  Stock  Splits
2022-03-08 09:57:00 05:30  09:57:00 05:30  15838.150391  ...      0       0

CodePudding user response:

You can filter datetime row with this.

df.Datetime = pd.to_datetime(df.Datetime)
df[df.Datetime.dt.second == 0].tail(1)
  • Related