0

Using python, how can I take the values from 2021-09-13 to 2021-09-16?

I tried the following:

date_start = df['date'].iloc[-4] #2021-09-13
date_end = df['date'].iloc[-1] #2021-09-16
df = df.loc[date_start:date_end]

but it returns only the rows for 2021-09-13 and 2021-09-16

index date value
2021-09-09 2021-09-09 10
2021-09-10 2021-09-10 20
2021-09-13 2021-09-13 30
2021-09-14 2021-09-14 40
2021-09-15 2021-09-15 50
2021-09-16 2021-09-16 60

Desired outcome:

index date value
2021-09-13 2021-09-13 30
2021-09-14 2021-09-14 40
2021-09-15 2021-09-15 50
2021-09-16 2021-09-16 60
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
kobo
  • 35
  • 6
  • 2
    Does this answer your question? [Select DataFrame rows between two dates](https://stackoverflow.com/questions/29370057/select-dataframe-rows-between-two-dates) – Tzane Sep 16 '21 at 13:33

1 Answers1

0

You can try this:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.random((200,1)))
df['index'] = pd.date_range('2021-9-1', periods=200, freq='D')
df['date'] = pd.date_range('2021-9-1', periods=200, freq='D')
mask = (df['date'] >= '2021-9-13') & (df['date'] <= '2021-9-16')
print(df.loc[mask])

Output:

           0      index       date
12  0.936342 2021-09-13 2021-09-13
13  0.357040 2021-09-14 2021-09-14
14  0.776492 2021-09-15 2021-09-15
15  0.543956 2021-09-16 2021-09-16
Sabil
  • 3,750
  • 1
  • 5
  • 16