我的数据框包含一列Date
& Time
,每行包含格式为MM/DD/YYYY HH:MM:SS
我希望能够仅根据日期范围对数据框进行切片,例如:5/01/2016 to 5/30/2016
。
任何建议都将不胜感激!
答案 0 :(得分:0)
表示变量sdate和edate
frame = []
record = 0
for date,time in my_list:
if date == sdate or record == 1:
frame.append([date,time])
record = 1
if date == edate:
break;
print (frame)
答案 1 :(得分:0)
您可以使用loc
选择满足条件(日期间隔)的数据框子集:
数据准备
In [13]: from io import StringIO
...: import pandas as pd
...:
In [14]: df = pd.read_csv(StringIO('''
...: Date
...: 5/01/2016 00:00:00
...: 5/02/2016 00:00:00
...: 5/03/2016 00:00:00
...: 5/04/2016 00:00:00
...: 5/05/2016 00:00:00
...: 5/06/2016 00:00:00
...: 5/07/2016 00:00:00
...: 5/08/2016 00:00:00
...: 5/09/2016 00:00:00
...: 5/010/2016 00:00:00
...: '''))
<强>运营强>
In [15]: df['Date'] = pd.to_datetime(df['Date'])
In [16]: start = "5/02/2016"
...: end = "5/05/2016"
In [17]: mask = (df['Date'] >= pd.to_datetime(start)) & (df['Date'] <= pd.to_datetime(end))
In [18]: df.loc[mask]
Out[18]:
Date
1 2016-05-02
2 2016-05-03
3 2016-05-04
4 2016-05-05