Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Numpy:数组的迭代组合_Python_Arrays_Numpy - Fatal编程技术网

Python Numpy:数组的迭代组合

Python Numpy:数组的迭代组合,python,arrays,numpy,Python,Arrays,Numpy,下面的代码旨在在旧的numpy基础上迭代构造一个新的numpy prv = np.array([[1,2],[3,4],[5,6]]) results = [] for i in prv: results.append(calc_something(i)) results = np.reshape(np.array(results), (prv.shape[0], 1)) combined = np.hstack((prv, results)) 问题是它会产生以下结果: [[1

下面的代码旨在在旧的numpy基础上迭代构造一个新的numpy

prv = np.array([[1,2],[3,4],[5,6]])

results = []
for i in prv:
    results.append(calc_something(i))

results = np.reshape(np.array(results), (prv.shape[0], 1))

combined = np.hstack((prv, results))
问题是它会产生以下结果:

[[1 2 array([6, 7, 3])]
 [3 4 array([3])]
 [5 6 array([9, 7])]]
而预期的结果是:

[[1,2,6],
 [1,2,7],
 [1,2,3],
 [3,4,3],
 [5,6,9],
 [5,6,7]]
为简单起见,我们假设函数
calc\u something(i)
返回如下值

def calc_something(i):
    if i[0] == 1:
        b = np.array([6,7,3])
        return b
    if i[0] == 3:
        b = np.array([3])
        return b
    if i[0] == 5:
        b = np.array([9,7])
        return b

需要更改哪些内容才能获得预期结果?

您可以
np.列堆栈
np的结果。沿零轴重复
,并将
计算某物()的结果串联起来。

输出:

array([[1, 2, 6],
       [1, 2, 7],
       [1, 2, 3],
       [3, 4, 3],
       [5, 6, 9],
       [5, 6, 7]])
arrray([[1, 2, 6],
        [1, 2, 7],
        [1, 2, 3],
        [3, 4, 3],
        [5, 6, 9],
        [5, 6, 7]])

使用当前的逻辑结构,此解决方案使用
np.column\u stack()
函数将返回的
calc()
函数值附加到扩展数组中

calc
函数,有一些小的调整:

def calc(i):
    if i[0] == 1:
        b = np.array([6, 7, 3])
    elif i[0] == 3:
        b = np.array([3])
    elif i[0] == 5:
        b = np.array([9, 7])
    return b
示例代码:

prv = np.arange(1, 7).reshape(-1, 2)
result = np.array((), dtype=int)

for i in prv:
    b = calc(i)
    c = np.column_stack((np.tile(i, b.size).reshape(-1, i.size), b))
    result = np.append(result, c)
    
r = result.reshape(-1, 3)
输出:

array([[1, 2, 6],
       [1, 2, 7],
       [1, 2, 3],
       [3, 4, 3],
       [5, 6, 9],
       [5, 6, 7]])
arrray([[1, 2, 6],
        [1, 2, 7],
        [1, 2, 3],
        [3, 4, 3],
        [5, 6, 9],
        [5, 6, 7]])
一般性意见:

使用数组值[1,3,5]和返回的数组作为键/值对,可以一起删除
calc
函数,并将其替换为简单的
dict
。然后,执行一个简单的
dict.get()
函数,而不是
calc
函数调用