假设我有两个NumPy数组,a
和b
:
a = np.array([
[1, 2, 3],
[2, 3, 4]
])
b = np.array([8,9])
我想将相同的数组追加b
到每一行(即添加多列)以获得一个数组,c
:
b = np.array([
[1, 2, 3, 8, 9],
[2, 3, 4, 8, 9]
])
如何在NumPy中轻松高效地做到这一点?
我特别担心它在大型数据集(a
比更大的数据集b
)中的行为,是否有办法创建许多副本(即a.shape[0]
)b
?
与这个问题有关,但是有多个值。
一种替代concatenate
方法是制作一个收件人数组,并将值复制到该收件人数组:
In [483]: a = np.arange(300).reshape(100,3)
In [484]: b=np.array([8,9])
In [485]: res = np.zeros((100,5),int)
In [486]: res[:,:3]=a
In [487]: res[:,3:]=b
采样时间
In [488]: %%timeit
...: res = np.zeros((100,5),int)
...: res[:,:3]=a
...: res[:,3:]=b
...:
...:
6.11 µs ± 20.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [491]: timeit np.concatenate((a, b.repeat(100).reshape(2,-1).T),1)
7.74 µs ± 15.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [164]: timeit np.concatenate([a, np.ones([a.shape[0],1], dtype=int).dot(np.array([b]))], axis=1)
8.58 µs ± 160 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句