Python 强制numpy保留一个列表一个列表

Python 强制numpy保留一个列表一个列表,python,numpy,Python,Numpy,x2_Kaxs是一个Nx3 numpy列表数组,这些列表中的元素索引到另一个数组中。我希望最终得到一个Nx3 numpy数组,其中包含这些索引元素的列表 x2_Kcids = array([ ax2_cid[axs] for axs in x2_Kaxs.flat ], dtype=object) 这将输出numpy阵列的(N*3)x1阵列。伟大的这几乎符合我的要求。我所需要做的就是重塑它 x2_Kcids.shape = x2_Kaxs.shape 这是可行的。x2_Kcids变成了一个N

x2_Kaxs
是一个Nx3 numpy列表数组,这些列表中的元素索引到另一个数组中。我希望最终得到一个Nx3 numpy数组,其中包含这些索引元素的列表

x2_Kcids = array([ ax2_cid[axs] for axs in x2_Kaxs.flat ], dtype=object)
这将输出numpy阵列的(N*3)x1阵列。伟大的这几乎符合我的要求。我所需要做的就是重塑它

x2_Kcids.shape = x2_Kaxs.shape
这是可行的。
x2_Kcids
变成了一个Nx3的numpy数组。太好了

除此之外,
x2_Kaxs
中的所有列表中只有一个元素。然后它变平了 它被转换成一个Nx3整数数组,我的代码希望稍后在管道中有一个列表

我提出的一个解决方案是附加一个虚拟元素,然后将其弹出,但这非常难看。还有更好的吗

类似于@Denis:

if x.ndim == 2:
    x.shape += (1,)

你的问题并不是关于大小为1的列表,而是关于大小相同的列表。我创建了以下虚拟示例:

ax2_cid = np.random.rand(10)
shape = (10, 3)

x2_Kaxs = np.empty((10, 3), dtype=object).reshape(-1)
for j in xrange(x2_Kaxs.size):
    x2_Kaxs[j] = [random.randint(0, 9) for k in xrange(random.randint(1, 5))]
x2_Kaxs.shape = shape

x2_Kaxs_1 = np.empty((10, 3), dtype=object).reshape(-1)
for j in xrange(x2_Kaxs.size):
    x2_Kaxs_1[j] = [random.randint(0, 9)]
x2_Kaxs_1.shape = shape

x2_Kaxs_2 = np.empty((10, 3), dtype=object).reshape(-1)
for j in xrange(x2_Kaxs_2.size):
    x2_Kaxs_2[j] = [random.randint(0, 9) for k in xrange(2)]
x2_Kaxs_2.shape = shape
如果我们在这三个上运行您的代码,则返回具有以下形状:

>>> np.array([ax2_cid[axs] for axs in x2_Kaxs.flat], dtype=object).shape
(30,)
>>> np.array([ax2_cid[axs] for axs in x2_Kaxs_1.flat], dtype=object).shape
(30, 1)
>>> np.array([ax2_cid[axs] for axs in x2_Kaxs_2.flat], dtype=object).shape
(30, 2)
所有列表长度为2的案例甚至不允许您将其重塑为
(n,3)
。问题是,即使使用
dtype=object
,numpy也会尽可能多地压缩输入,如果所有列表的长度相同,则会一直压缩到单个元素。我认为您最好的选择是预先分配您的
x2kcids
数组:

x2_Kcids = np.empty_like(x2_Kaxs).reshape(-1)
shape = x2_Kaxs.shape
x2_Kcids[:] = [ax2_cid[axs] for axs in x2_Kaxs.flat]
x2_Kcids.shape = shape

编辑由于联合国大学的答案不再可见,我打算从他那里偷东西。上面的代码可以写得更漂亮、更简洁:

x2_Kcids = np.empty_like(x2_Kaxs)
x2_Kcids.ravel()[:] = [ax2_cid[axs] for axs in x2_Kaxs.flat]

在上述单个项目列表示例中:

>>> x2_Kcids_1 = np.empty_like(x2_Kaxs_1).reshape(-1)
>>> x2_Kcids_1[:] = [ax2_cid[axs] for axs in x2_Kaxs_1.flat]
>>> x2_Kcids_1.shape = shape
>>> x2_Kcids_1
array([[[ 0.37685372], [ 0.95328117], [ 0.63840868]],
       [[ 0.43009678], [ 0.02069558], [ 0.32455781]],
       [[ 0.32455781], [ 0.37685372], [ 0.09777559]],
       [[ 0.09777559], [ 0.37685372], [ 0.32455781]],
       [[ 0.02069558], [ 0.02069558], [ 0.43009678]],
       [[ 0.32455781], [ 0.63840868], [ 0.37685372]],
       [[ 0.63840868], [ 0.43009678], [ 0.25532799]],
       [[ 0.02069558], [ 0.32455781], [ 0.09777559]],
       [[ 0.43009678], [ 0.37685372], [ 0.63840868]],
       [[ 0.02069558], [ 0.17876822], [ 0.17876822]]], dtype=object)
>>> x2_Kcids_1[0, 0]
array([ 0.37685372])

@自从你删除了你的答案,我就厚颜无耻地在我的答案编辑中复制了你作业左边的扁平数组。但是必须使用
.ravel()
,因为
.flat
会产生奇怪的结果。