在Python中子集所选天数数据

Har*_*hid 3 python time-series dataframe pandas

我有一些时间序列数据为:

import pandas as pd    
index = pd.date_range('06/01/2014',periods=24*30,freq='H')
df1 = pd.DataFrame(range(len(index)),index=index)
Run Code Online (Sandbox Code Playgroud)

现在我想对以下日期的数据进行子集

selec_dates = ['2014-06-10','2014-06-15','2014-06-20']
Run Code Online (Sandbox Code Playgroud)

我尝试了以下声明,但不起作用

sub_data = df1.loc[df1.index.isin(pd.to_datetime(selec_dates))]
Run Code Online (Sandbox Code Playgroud)

我在哪里做错了?是否有其他方法来选择子集的选定日期数据?

jez*_*ael 6

您需要比较dates并供测试成员资格使用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
...
Run Code Online (Sandbox Code Playgroud)

如果要使用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
...
Run Code Online (Sandbox Code Playgroud)