0

I have a dataframe that looks like this

    Date            MBs     GBs
0   2018-08-14 20:10    32.00 MB    0.00 GB
1   2018-08-14 20:05    4.00 MB     0.00 GB
2   2018-08-14 20:00    1000.99 MB  1.23 GB

Ive already done this :

na_aus['Date'] =  pd.to_datetime(na_aus['Date'], format='%Y-%m-%d %H:%M:%S')

But when i try to do a simple filter like this :

na_aus.loc['2018-08-14 19:50' : '2018-08-14 20:10'] 

All I get is:

Date            MBs     GBs

With no data returned.

I tried following this Select dataframe rows between two dates but its not working

chowpay
  • 1,515
  • 6
  • 22
  • 44
  • https://stackoverflow.com/questions/28437460/pandas-slice-dataframe-by-datetime-that-may-not-exist-and-return-view – BENY Aug 15 '18 at 00:22

1 Answers1

1

use .between:

na_aus.loc[na_aus['Date'].between('2018-08-14 19:50','2018-08-14 20:10')]

In your case, all rows satisfy the requirement:

                 Date         MBs      GBs
0 2018-08-14 20:10:00    32.00 MB  0.00 GB
1 2018-08-14 20:05:00     4.00 MB  0.00 GB
2 2018-08-14 20:00:00  1000.99 MB  1.23 GB

But if you don't want it to include the boundaries, set inclusive=False. This means that because row 0 is the exact border of your range, it won't be included:

>>> na_aus.loc[na_aus['Date'].between('2018-08-14 19:50', '2018-08-14 20:10',
                                      inclusive=False)]


                 Date         MBs      GBs
1 2018-08-14 20:05:00     4.00 MB  0.00 GB
2 2018-08-14 20:00:00  1000.99 MB  1.23 GB
sacuL
  • 49,704
  • 8
  • 81
  • 106
  • Glad I could help! – sacuL Aug 14 '18 at 23:59
  • actually can you add your example for multiple ranges. For instance, if you wanted 2018-08-13 19:50','2018-08-14 20:10 slice and also 2018-08-12 19:50','2018-08-12 20:10 for example but not the rest so I only have a DF of ranges I want is that possible? – chowpay Aug 15 '18 at 00:00
  • 2
    use `|` operator .. `df.loc[df.between(a, b) | df.between(c, d)]` – rafaelc Aug 15 '18 at 00:01
  • I was about to say the same as @RafaelC – sacuL Aug 15 '18 at 00:01