1

I'm trying to generate 50 random samples of 30 continuous day periods from a list of corn prices (which is index by date).

So far I've got 'select 50 random days' on line one. For the second line, what I really want is an array of dataframes, each one containing 30 days from sample date. Currently it just returns the price on that day.

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

What's the cleanest way of doing that?

5
  • what is corn before hand? Commented May 3, 2016 at 12:56
  • corn['Open'] is a pandas series of the form (date, price) where date is the index. Commented May 3, 2016 at 13:00
  • I haven't used pandas / numpy much but would zip(samples, corn["Open"][samples]) be what you are looking for? Commented May 3, 2016 at 13:05
  • 2
    I couldn't understand based on your description. Can you give a sample table? How should it look like? Commented May 3, 2016 at 13:23
  • You could also use pandas' sample method to get random samples, I find it more elegant than the numpy method. Commented May 3, 2016 at 13:47

1 Answer 1

2

You could use

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

to select 30 days worth of rows starting from date date. Note that .loc[start:end] includes both start and end (unlike Python slices, which use half-open intervals). Thus adding 29 days to date results in a DataFrame of length 30.

To get an list of DataFrames, use a list comprehension:

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Very clever, just what I was looking for. Thanks very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.