我有一些时间序列数据:
import pandas as pd
index = pd.date_range('06/01/2014',periods=24*30,freq='H')
df1 = pd.DataFrame(range(len(index)),index=index)
现在我想对以下日期的数据进行子集化
selec_dates = ['2014-06-10','2014-06-15','2014-06-20']
我尝试了以下语句,但它不起作用
sub_data = df1.loc[df1.index.isin(pd.to_datetime(selec_dates))]
我哪里做错了?是否有任何其他方法来对选定日期数据进行子集化?
最佳答案
您需要比较日期
和测试成员(member)使用numpy.in1d
:
sub_data = df1.loc[np.in1d(df1.index.date, pd.to_datetime(selec_dates).date)]
print (sub_data)
a
2014-06-10 00:00:00 216
2014-06-10 01:00:00 217
2014-06-10 02:00:00 218
2014-06-10 03:00:00 219
2014-06-10 04:00:00 220
2014-06-10 05:00:00 221
2014-06-10 06:00:00 222
2014-06-10 07:00:00 223
2014-06-10 08:00:00 224
2014-06-10 09:00:00 225
2014-06-10 10:00:00 226
...
如果要使用isin
,必须创建具有相同索引的Series
:
sub_data = df1.loc[pd.Series(df1.index.date, index=df1.index)
.isin(pd.to_datetime(selec_dates).date)]
print (sub_data)
a
2014-06-10 00:00:00 216
2014-06-10 01:00:00 217
2014-06-10 02:00:00 218
2014-06-10 03:00:00 219
2014-06-10 04:00:00 220
2014-06-10 05:00:00 221
2014-06-10 06:00:00 222
2014-06-10 07:00:00 223
2014-06-10 08:00:00 224
2014-06-10 09:00:00 225
2014-06-10 10:00:00 226
2014-06-10 11:00:00 227
...
关于python - 在 Python 中对选定的日期数据进行子集化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43935214/