高级数组/数据帧切片(numpy / pandas)

时间:2016-05-03 12:54:00

标签: python numpy pandas

我正在尝试从玉米价格列表(按日期索引)生成50个连续日期的50个随机样本。

到目前为止,我已经在第一行'选择了50个随机日'。对于第二行,我真正想要的是一组数据帧,每个数据帧包含30天的采样日期。目前它只返回当天的价格。

samples=np.random.choice(corn[:'1981'].index,50)
corn['Open'][samples] #line I need to fix

最干净的方法是什么?

1 个答案:

答案 0 :(得分:3)

您可以使用

corn.loc[date:date+pd.Timedelta(days=29)]

从日期date开始选择30天的行。请注意,.loc[start:end]包括startend(与使用半开放区间的Python切片不同)。因此,向date添加29天会产生长度为30的DataFrame。

要获取DataFrames列表,请使用列表解析:

dfs = [corn.loc[date:date+pd.Timedelta(days=29)] for date in samples]
import numpy as np
import pandas as pd

N = 365
corn = pd.DataFrame({'Open': np.random.random(N)}, 
                    index=pd.date_range('1980-1-1', periods=N))
samples = np.random.choice(corn[:'1981'].index,50)
dfs = [corn.loc[date:date+pd.Timedelta(days=29)] for date in samples]