将numpy数组扩展到具有自己内容的特定范围

时间:2016-01-26 01:58:14

标签: python arrays numpy

使用自己的值扩展数组到特定大小的最有效方法是什么?

import numpy as np

# For this example, lets use an array with 4 items
data = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]]) # 4 items

# I want to extend it to 10 items, here's the expected result would be:
data = np.array([[ 0,  1,  2],
                 [ 3,  4,  5],
                 [ 6,  7,  8],
                 [ 9, 10, 11],
                 [ 0,  1,  2],
                 [ 3,  4,  5],
                 [ 6,  7,  8],
                 [ 9, 10, 11],
                 [ 0,  1,  2],
                 [ 3,  4,  5]])

2 个答案:

答案 0 :(得分:3)

您可以连接数组:

.timelinefull {
    display: inline;
}

.timeline-inner {
    display: inline;
}

.info {
    display: inline;
    padding-top: 10px;
    position: absolute;
    z-index: 100;
    -webkit-transition:all linear 0.3s;
    transition:all linear 0.3s;
}

.line {
    box-shadow: 0 0 0 2px rgba(0,0,0,.05);
    margin-left: -5px;
    margin-right: -5px;
}

.info.ng-hide {
    opacity:0;
}

a:link {
    text-decoration: none;
}

答案 1 :(得分:1)

我能想到的最有效的方法是使用itertools模块。首先创建每行的循环(无限迭代器),然后使用islice()获取所需的行数。结果必须是元组或列表,因为numpy requires the length of the array to be explicit at construction time

import itertools as it

def extend_array(arr, length):
    return np.array(tuple(it.islice(it.cycle(arr), length)))

用法:

>>> data = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
>>> extend_array(data, 10)
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [ 0,  1,  2],
       [ 3,  4,  5]])