如何在NumPy数组中添加额外的列 [英] How to add an extra column to a NumPy array
本文介绍了如何在NumPy数组中添加额外的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个NumPy数组,a
:
Let’s say I have a NumPy array, a
:
a = np.array([
[1, 2, 3],
[2, 3, 4]
])
我想添加一列零以获取数组,b
:
And I would like to add a column of zeros to get an array, b
:
b = np.array([
[1, 2, 3, 0],
[2, 3, 4, 0]
])
如何在NumPy中轻松地做到这一点?
How can I do this easily in NumPy?
推荐答案
我认为更简单,启动更快捷的解决方案是执行以下操作:
I think a more straightforward solution and faster to boot is to do the following:
import numpy as np
N = 10
a = np.random.rand(N,N)
b = np.zeros((N,N+1))
b[:,:-1] = a
时间:
In [23]: N = 10
In [24]: a = np.random.rand(N,N)
In [25]: %timeit b = np.hstack((a,np.zeros((a.shape[0],1))))
10000 loops, best of 3: 19.6 us per loop
In [27]: %timeit b = np.zeros((a.shape[0],a.shape[1]+1)); b[:,:-1] = a
100000 loops, best of 3: 5.62 us per loop
这篇关于如何在NumPy数组中添加额外的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文