【问题标题】:How to construct a new numpy array from a set of existing arrays?如何从一组现有数组中构造一个新的 numpy 数组?
【发布时间】:2015-09-11 09:12:27
【问题描述】:

我有 12 个 numpy 数组,5 个大小为 (3, 121) 和 7 个大小为 (3, 120),排序为 0-11;称它们为 a0、a1、...、a11。我想通过以下方式专门构建一个新数组:

newArray = [a0_00, a1_00, a2_00, ..., a11_00, a0_01, a1_01, ..., a11_01, a0_02...]

也就是说,我想从 12 个数组中的每个数组中取出第一列并将它们按顺序添加到我的新数组中,然后从 12 个数组中的每个数组中取出第二列,等等。 ..

我最近尝试的只是将每个数组的前 12 个值重复到整个新数组 timedata...

for i in range(len(files)):
    data = loadtxt(files[i], skiprows=4, delimiter=',').T[0:,:]
    timedata[i::12] = data[0,0]

我尝试过嵌套 for 循环并以不同的方式索引数组,但到目前为止还没有任何工作......任何想法将不胜感激。

谢谢

【问题讨论】:

  • 重新实现 zip,使其在获得第一个 StopIteration 或使用 itertools.zip_longest 后不会终止

标签: python arrays loops numpy indexing


【解决方案1】:

您基本上有一个 12 x 3 x(120 或 121)的锯齿状数组。如果 a05 到 a11 的最后一列被填满,这会容易一些。相反,您可以遍历从 0 到 120 的列;并遍历数组;并且仅当该列存在时才将该列添加到新数组中。

这里是一些示例代码。请注意,我使用了 11 和 12 的长度而不是 120 和 121,但想法是相同的。

import numpy as np

np.random.seed(1000)
a01 = np.random.randint(0,10, (3,12))
a02 = np.random.randint(0,10, (3,12))
a03 = np.random.randint(0,10, (3,12))
a04 = np.random.randint(0,10, (3,12))
a05 = np.random.randint(0,10, (3,12))
a06 = np.random.randint(0,10, (3,11))
a07 = np.random.randint(0,10, (3,11))
a08 = np.random.randint(0,10, (3,11))
a09 = np.random.randint(0,10, (3,11))
a10 = np.random.randint(0,10, (3,11))
a11 = np.random.randint(0,10, (3,11))
arrayList = [a01, a02, a03, a04, a05, a06, a07, a08, a09, a10, a11]
cols = np.sum([a.shape[1] for a in arrayList])
newArray = np.zeros((3,cols))

arrIndex = 0
for i in range(12):
    for a in arrayList:
        try: 
            newArray[:,arrIndex] = a[:,i]
            arrIndex = arrIndex + 1
        except IndexError:
            pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2013-07-10
    • 2017-03-17
    • 1970-01-01
    • 2018-10-12
    相关资源
    最近更新 更多