从列表的ndarray转换为ndarray

问题描述 投票:0回答:2

从列表的2d ndarray转换为3d ndarray,我使用类似于下面的代码创建了.npy文件。如何从(2,2)转换为(2,2,3)ndarray?

dtypes = [('value_model', np.float64),
         ('value_simulator', np.float64), 
         ('vector_optimum', object)]

results = np.zeros((2,2), dtype = dtypes) 

for i in range(2):
    for j in range(2):
        results['vector_optimum'][i, j] = list(range(1+i+2*j,4+i+2*j))

print(results['vector_optimum'])
"""
[[list([1, 2, 3]) list([3, 4, 5])]
 [list([2, 3, 4]) list([4, 5, 6])]]
"""
results['vector_optimum'].shape
#Out[4]: (2, 2)   

如何将结果['vector_optimum']从(2,2)转换为(2,2,3)ndarray?

python numpy numpy-ndarray
2个回答
0
投票

尝试下面的代码

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

输出:

(2, 2, 1)

0
投票

您必须一口气改变结果的“形状”。它的形状必须为(2, 2)(2, 2, 3)

对于您的示例,我将只使用一个新变量,如下所示:

import numpy as np


dtypes = [
    ('value_model', np.float64),
    ('value_simulator', np.float64),
    ('vector_optimum', object)
]

results = np.zeros((2, 2), dtype = dtypes)
new_results = np.zeros((2, 2, 3), dtype = dtypes)

for i in range(2):
    for j in range(2):
        new_results['vector_optimum'][i][j] = np.array(range(1+i+2*j,4+i+2*j))

print(new_results['vector_optimum'])
"""
[[[1 2 3]
  [3 4 5]]

 [[2 3 4]
  [4 5 6]]]
"""
new_results['vector_optimum'].shape
#Out[4]: (2, 2, 3)
© www.soinside.com 2019 - 2024. All rights reserved.