从多个特定日期选择大熊猫中的数据

时间:2018-10-30 22:59:31

标签: python-3.x pandas dataframe

dft = pd.DataFrame(randn(100000,1), columns=['A'],
     index=pd.date_range('20130101',periods=100000,freq='T'))

如您所见,我以10分钟的间隔将日期框架从“ 2013-01-01”初始化为“ 2013-03-11”。如何从特定条件中选择特定数据?

1)列表中的日期 例如:如果有清单['2013-01-02','2013-01-04','2013-01-06']    如何选择此清单日期的数据?或者如何选择不在该列表日期的数据? 更具体地说,“ 2013-01-02”表示从“ 2013-01-02 00:00:00”到“ 2013-01-02 23:50:00”的所有数据。

2)多个切片选择 例如:我希望可以在多个切片中选择数据,如下所示: ['2013-01-02':'2013-01-03']&['2013-01-05':'2013-01-07']&['2013-01-09':'2013-01- 11'] 更具体地说,此切片应与python切片相同,这意味着包括左但不包括右。

1 个答案:

答案 0 :(得分:2)

假设这是原始数据(索引为Datetime

dft = pd.DataFrame(np.random.randn(100000,1), columns=['A'],
     index=pd.date_range('20130101',periods=100000,freq='T'))
dft.head()
                            A
2013-01-01 00:00:00  0.313644
2013-01-01 00:01:00  0.458860
2013-01-01 00:02:00  0.841434
2013-01-01 00:03:00 -0.135846
2013-01-01 00:04:00 -0.881316

对于1),只需使用.isin()

myDates = ['2013-01-02', '2013-01-04', '2013-01-06']

# to get data in list
df_in = dft[pd.to_datetime(dft.index.date).isin(myDates)]
df_in.head()
                            A
2013-01-02 00:00:00  0.444005
2013-01-02 00:01:00 -0.073561
2013-01-02 00:02:00  0.256737
2013-01-02 00:03:00  1.304807
2013-01-02 00:04:00 -0.741956

# to get data not in list
df_not_in = dft[~pd.to_datetime(dft.index.date).isin(myDates)]
df_not_in_list.head()
                            A
2013-01-01 00:00:00 -0.944070
2013-01-01 00:01:00  0.225456
2013-01-01 00:02:00  0.571424
2013-01-01 00:03:00 -0.004389
2013-01-01 00:04:00  0.933229

对于2),如果我理解正确,则希望使用多个日期时间片来选择数据。为此,您可以使用嵌套列表中的multiple index masks按日期进行过滤

myDates = [['2013-01-02','2013-01-03'],
           ['2013-01-05','2013-01-07'],
           ['2013-01-09','2013-01-11']]
df_masked = dft[
      (dft.index >= myDates[0][0]) & (dft.index <= myDates[0][1]) & \
      (dft.index >= myDates[1][0]) & (dft.index <= myDates[1][1]) & \
      (dft.index >= myDates[2][0]) & (dft.index <= myDates[2][1])
      ]