如果我尝试如何将元组追加到一个numpy数组而不需要元素化地执行它?
x = np.append(x, (2,3))
元组(2,3)
不会被追加到数组,而2
和3
获得单独追加的结束,即使我最初宣布x
作为
x = np.array([], dtype = tuple)
或
x = np.array([], dtype = (int,2))
这样做的正确方法是什么?
如果我尝试如何将元组追加到一个numpy数组而不需要元素化地执行它?
x = np.append(x, (2,3))
元组(2,3)
不会被追加到数组,而2
和3
获得单独追加的结束,即使我最初宣布x
作为
x = np.array([], dtype = tuple)
或
x = np.array([], dtype = (int,2))
这样做的正确方法是什么?
我同意@ user2357112评论:
追加到NumPy的阵列是灾难性不是追加到普通名单慢。这是他们是不是在所有设计
的操作这里有一个小基准:
# 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
编辑
这里是我的笔记本电脑的标杆输出:
[成品在14.3s]
如果我明白你的意思,你可以使用vstack
:
>>> a = np.array([(1,2),(3,4)])
>>> a = np.vstack((a, (4,5)))
>>> a
array([[1, 2],
[3, 4],
[4, 5]])
这听起来像提问者正在寻找的完全相反。 – user2357112
@ user2357112谢谢。我已经改变了我的回答 –
您需要提供的形状numpy的D类,像这样:
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
您生成了一个包含'dtype'作为对象的数组。那有什么价值? – hpaulj
np.append
很容易用等的情况下使用:
In [94]: np.append([1,2,3],4)
Out[94]: array([1, 2, 3, 4])
但它的第一个例子很难明白了。它显示了相同类型的平板连击的你烦恼:
>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
剥离的三维测试,np.append
确实
In [166]: np.append(np.array([1,2],int),(2,3))
Out[166]: array([1, 2, 2, 3])
In [167]: np.concatenate([np.array([1,2],int),np.array((2,3))])
Out[167]: array([1, 2, 2, 3])
所以除了你需要了解什么np.array((2,3))
做最简单的情况,以及如何concatenate
处理尺寸。
因此,除了速度问题,np.append
可能会更棘手的使用接口建议。列表append
的相似之处仅仅是肤浅的。
至于append
(或concatenate
)与dtype=object
(不dtype=tuple
)或复合dtype
(“我,我”),我不能告诉你,没有测试会发生什么。至少输入应该已经是数组,并且应该有匹配的dtype
。否则结果可能无法预测。
你为什么要追加到NumPy数组?这几乎从来都不是一个好主意。 – user2357112
@ user2357112因为我处于无法预先知道阵列中有多少元素的情况。此外,我的印象是,追加'numpy'的速度要快于python – Anonymous
'追加到NumPy数组的** **灾难性**比追加到普通列表慢。这是一种他们根本没有设计的操作。 – user2357112