如何将元组附加到numpy数组,而不必按元素执行它?

2024-04-20 09:37:19 发布

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

如果我试着

x = np.append(x, (2,3))

元组(2,3)不会附加到数组的末尾,而是23单独附加,即使我最初声明x

x = np.array([], dtype = tuple)

或者

x = np.array([], dtype = (int,2))

正确的方法是什么?


Tags: 方法声明np数组arrayint元组dtype
3条回答

如果我明白你的意思,你可以使用vstack

>>> a = np.array([(1,2),(3,4)])
>>> a = np.vstack((a, (4,5)))
>>> a
array([[1, 2],
       [3, 4],
       [4, 5]])

我同意@user2357112的意见:

appending to NumPy arrays is catastrophically slower than appending to ordinary lists. It's an operation that they are not at all designed for

下面是一个小基准:

# measure execution time
import timeit
import numpy as np


def f1(num_iterations):
    x = np.dtype((np.int32, (2, 1)))

    for i in range(num_iterations):
        x = np.append(x, (i, i))


def f2(num_iterations):
    x = np.array([(0, 0)])

    for i in range(num_iterations):
        x = np.vstack((x, (i, i)))


def f3(num_iterations):
    x = []
    for i in range(num_iterations):
        x.append((i, i))

    x = np.array(x)

N = 50000

print timeit.timeit('f1(N)', setup='from __main__ import f1, N', number=1)
print timeit.timeit('f2(N)', setup='from __main__ import f2, N', number=1)
print timeit.timeit('f3(N)', setup='from __main__ import f3, N', number=1)

我既不使用np.append也不使用vstack,我只需要正确地创建python数组,然后使用它来构造np.array

编辑

这是我笔记本电脑上的基准输出:

  • 附:12.4983000173
  • 垂直缝:1.60663705793
  • 清单:0.0252208517006

[在14.3秒内完成]

您需要将形状提供给numpy dtype,如下所示:

x = np.dtype((np.int32, (1,2))) 
x = np.append(x,(2,3))

输出

array([dtype(('<i4', (2, 3))), 1, 2], dtype=object)

[参考文献][1]http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html

相关问题 更多 >