Pandas:使用日期列表和 DateTimeIndex 访问数据
Pandas: Accessing data with list of dates and DateTimeIndex
我有一个 pandas DataFrame 和 DateTimeIndex
:
A B
2016-04-25 18:50:06 440.967796 201.049600
2016-04-25 18:50:13 441.054995 200.767034
2016-04-25 18:50:20 441.142337 200.484475
...
2016-07-27 18:50:06 440.967796 201.049600
2016-07-27 18:50:13 441.054995 200.767034
2016-07-27 18:50:20 441.142337 200.484475
我想使用日期列表提取给定日期 yyyy-mm-dd
的所有数据:['2016-04-25','2016-04-28',...]
我尝试了以下方法:
df[df.index.isin(['2016-04-25', '2016-04-26'])]
Empty DataFrame
我想检索此列表中给出日期的所有数据(全天数据)
您需要先删除时间 :
df = df[df.index.normalize().isin(['2016-04-25', '2016-04-26'])]
df = df[df.index.floor('D').isin(['2016-04-25', '2016-04-26'])]
另一个解决方案是比较 DatetimeIndex.date
, but necessary use numpy.in1d
而不是 isin
:
df = df[np.in1d(df.index.date, pd.to_datetime(['2016-04-25', '2016-04-26']).date)]
或比较创建的字符串 DatetimeIndex.strftime
:
df = df[np.in1d(df.index.strftime('%Y-%m-%d'), ['2016-04-25', '2016-04-26'])]
print (df)
A B
2016-04-25 18:50:06 440.967796 201.049600
2016-04-25 18:50:13 441.054995 200.767034
2016-04-25 18:50:20 441.142337 200.484475
我有一个 pandas DataFrame 和 DateTimeIndex
:
A B
2016-04-25 18:50:06 440.967796 201.049600
2016-04-25 18:50:13 441.054995 200.767034
2016-04-25 18:50:20 441.142337 200.484475
...
2016-07-27 18:50:06 440.967796 201.049600
2016-07-27 18:50:13 441.054995 200.767034
2016-07-27 18:50:20 441.142337 200.484475
我想使用日期列表提取给定日期 yyyy-mm-dd
的所有数据:['2016-04-25','2016-04-28',...]
我尝试了以下方法:
df[df.index.isin(['2016-04-25', '2016-04-26'])]
Empty DataFrame
我想检索此列表中给出日期的所有数据(全天数据)
您需要先删除时间
df = df[df.index.normalize().isin(['2016-04-25', '2016-04-26'])]
df = df[df.index.floor('D').isin(['2016-04-25', '2016-04-26'])]
另一个解决方案是比较 DatetimeIndex.date
, but necessary use numpy.in1d
而不是 isin
:
df = df[np.in1d(df.index.date, pd.to_datetime(['2016-04-25', '2016-04-26']).date)]
或比较创建的字符串 DatetimeIndex.strftime
:
df = df[np.in1d(df.index.strftime('%Y-%m-%d'), ['2016-04-25', '2016-04-26'])]
print (df)
A B
2016-04-25 18:50:06 440.967796 201.049600
2016-04-25 18:50:13 441.054995 200.767034
2016-04-25 18:50:20 441.142337 200.484475