Using datetime and a dataframe, I want to find which rows fall within the range of dates I have specified.
Sample dataframe:
times = pd.date_range(start="2018-01-01",end="2020-02-02")
values = np.random.rand(512)
# Make df
df = pd.DataFrame({'Time' : times,
'Value': values})
How do I easily select all values that fall within a certain month or range?
I feel like a good step is using:
pd.to_datetime(df['Time']).dt.to_period('M')
>>> df
0 2018-01
1 2018-02
2 2018-03
But I wouldn't know how to contine. I would like to be able to select a year/month like 2019-01
or a range 2019-01:2020-01
to find the indices in the dataframe that the input.
CodePudding user response:
I apparently did the right thing already, but had a wrong syntax.
It was quick, but just to be sure here is the answer:
np.where(pd.to_datetime(df['time']).dt.to_period('M') == '2018-01')
Then a range can be specified as well.
CodePudding user response:
With query
you can also select date ranges pretty quickly:
df.query('"2019-01-01" <= Time < "2019-02-01"')