Numpy:将最后一个轴转换为lis

2024-03-28 15:59:57 发布

您现在位置:Python中文网/ 问答频道 /正文

让numpy数组是shape(x,y,z)。 我希望它是(x,y)形状,每个元素都是z长度的列表:[a, b, c, ..., z] 有什么办法可以用numpy方法来做吗?你知道吗


Tags: 方法numpy元素列表数组形状shape办法
2条回答

我无法想象为什么numpy会需要这样的方法。这是,或多或少,一个肾盂解决方案。你知道吗

import numpy as np
# an example array with shape [2,3,4] 
a = np.random.random([2,3,4])

# create the target array shaped [2,3] with 'object' type (accepting other types than numbers).
b = np.array([[None for row in mat] for mat in a])
for i in range(b.shape[0]):
   for j in range(b.shape[1]):
      b[i,j] = list(a[i,j])

您可以使用tolist并指定给预分配的对象数组:

import numpy as np

a = np.random.randint(0,10,(100,100,100))

def f():
    A = np.empty(a.shape[:-1],object)
    A[...] = a.tolist()
    return A

f()[99,99]
# [4, 5, 9, 2, 8, 9, 9, 6, 8, 5, 7, 9, 8, 7, 6, 1, 9, 6, 2, 9, 0, 7, 0, 1, 2, 8, 4, 4, 7, 0, 1, 2, 3, 8, 9, 6, 0, 1, 4, 7, 0, 7, 9, 3, 9, 1, 8, 7, 1, 2, 3, 6, 6, 2, 7, 0, 2, 8, 7, 0, 0, 1, 8, 2, 6, 3, 5, 4, 9, 6, 9, 0, 2, 5, 9, 5, 3, 7, 0, 1, 9, 0, 8, 2, 0, 7, 3, 6, 9, 9, 4, 4, 3, 8, 4, 7, 4, 2, 1, 8]
type(f()[99,99])
# <class 'list'>

from timeit import timeit
timeit(f,number=100)*10
# 28.67872992530465

相关问题 更多 >