| xs, n=None): | |
| """Draw a sample from xs with the same length as xs. | |
| xs: sequence | |
| n: sample size (default: len(xs)) | |
| returns: NumPy array | |
| """ | |
| if n is None: | |
| n = len(xs) | |
| return np.random.choice(xs, n, replace=True) | |
| def SampleRows(df, nrows, replace=False): | |
| """Choose a sample of rows from a DataFrame. | |
| df: DataFrame | |
| nrows: number of rows | |
| replace: whether to sample with replacement | |
| returns: DataDf | |
| """ | |
| indices = np.random.choice(df.index, nrows, replace=replace) | |
| sample = df.loc[indices] | |
| return sample | |
| def ResampleRows(df): | |
| """Resamples rows from a DataFrame. | |
| df: DataFrame | |
| returns: DataFrame | |
| """ | |
| return SampleRows(df, len(df), replace=True) | |
| def ResampleRowsWeighted(df, column='finalwgt'): | |
| """Resamples a DataFrame using probabilities proportional to given column. | |
| df: DataFrame | |
| column: string column name to use as weights | |
| returns: DataFrame | |
| """ | |
| weights = df[column] | |
| cdf = Cdf(dict(weights)) | |
| indices = cdf.Sample(len(weights)) | |
| sample = df.loc[indices] | |
| return sample | |
| def PercentileRow(array, p): | |
| """Selects the row from a sorted array that maps to percentile p. | |
| p: float 0--100 | |
| returns: NumPy array (one row) | |
| """ | |
| rows, cols = array.shape | |
| index = int(rows * p / 100) | |
| return array[index,] | |
| def PercentileRows(ys_seq, percents): | |
| """Given a collection of lines, selects percentiles along vertical axis. | |
| For example, if ys_seq contains simulation results like ys as a | |
| function of time, and percents contains (5, 95), the result would | |
| be a 90% CI for each vertical slice of the simulation results. | |
| ys_seq: sequence of lines (y values) | |
| percents: list of percentiles (0-100) to select | |
| returns: list of NumPy arrays, one for each pe |