Bootstrap
本文主要介绍使用Python numpy将数组中所有元素,通过一定的规则将数据元素进行重复生成,也就是成倍的生成数据。效果示例如下:
l = np.array([3,4,5,6,7])

生成n倍,加倍在每次重复的值。当n=3时,结果如下:

[3, 4, 5, 6, 7, 6,  8, 10, 12, 14, 12, 16, 20, 24, 28]

1、numpy.outer和numpy.ndarray.ravel复重生成

>>> a = np.array([3,4,5,6,7])                                                                                          
>>> n = 3
>>> factors = 2**np.arange(n)
>>> np.outer(factors, a).ravel()
array([ 3, 4, 5, 6, 7, 6, 8, 10, 12, 14, 12, 16, 20, 24, 28])

2、使用concatenate进行重复

l = np.array([3,4,5,6,7])
final = np.concatenate([l*2**(i) for i in range(3)])
print (final)
array([ 3, 4, 5, 6, 7, 6, 8, 10, 12, 14, 12, 16, 20, 24, 28])

3、使用flatten通过填写倍数方式生成

l = np.array([3,4,5,6,7])
>>> (l * [[1], [2], [4]]).flatten()
array([ 3, 4, 5, 6, 7, 6, 8, 10, 12, 14, 12, 16, 20, 24, 28])

4、使用reshape和flatten生成

import numpy as np
l = np.array([3, 4, 5, 6, 7])
rows = np.tile(l, 3).reshape(-1, len(l)) * np.power(2, np.arange(3)).reshape(-1, 1)
print(rows.flatten())

输出

[ 3  4  5  6  7  6  8 10 12 14 12 16 20 24 28]

5、使用np.power和np.ndarray.ravel生成

A = np.array([3,4,5,6,7])
res = (A * np.power(2, np.arange(3))[:, None]).ravel()
print(res)

输出

array([ 3,  4,  5,  6,  7,  6,  8, 10, 12, 14, 12, 16, 20, 24, 28])