python - 强制 numpy 保留一个列表

标签 python numpy

x2_Kaxs 是一个 Nx3 numpy 列表数组,这些列表中的元素索引到另一个数组。我想以这些索引元素列表的 Nx3 numpy 数组结束。

x2_Kcids = array([ ax2_cid[axs] for axs in x2_Kaxs.flat ], dtype=object)

这会输出一个 (N*3)x1 数组的 numpy 数组。伟大的。这几乎适用于我想要的东西。我需要做的就是 reshape 它。

x2_Kcids.shape = x2_Kaxs.shape

这行得通。x2_Kcids 变成了一个 Nx3 的 numpy 数组。完美的。

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

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

最佳答案

您的问题实际上与大小为 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 的情况甚至不允许您 reshape 为 (n, 3)。问题是,即使使用 dtype=object,numpy 也会尽可能地尝试 numpy 您的输入,如果所有列表都是同样的长度。我认为您最好的选择是预分配您的 x2_Kcids 数组:

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

编辑 由于 unubtu 的答案不再可见,我打算从他那里窃取。上面的代码可以写得更漂亮、更紧凑:

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])

关于python - 强制 numpy 保留一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15415858/

相关文章:

python - 无法使用 pip3 在 Python 3.5.3 上安装 mysql-connector

python - 拉伸(stretch)列表以适应彼此的尺寸

python - Airflow 回填作业失败,即使测试工作正常

python mysql 插入 float 精度

python - 递归嵌套列表

python - 传播计算结果

python - 对 4D numpy 数组进行排序,但保持一个轴连接在一起

Python numpy 计算第一个特征值和特征向量

python - 我有一个带有两个独立离散变量的高斯函数。如何创建所有可能值的矩阵?

c# - 失去网络连接时 ZMQ 发布-订阅程序失败