简体   繁体   English

在 numpy 数组中添加具有特定值的列的最快方法?

[英]Fastest way to add a column in numpy array with a specific value?

This is most likely a duplicate;这很可能是重复的; apologies as I couldn't find the answer.抱歉,我找不到答案。 I have a (3000, 3) array and I want to make a (3000, 4) array with the last column being a specific value.我有一个 (3000, 3) 数组,我想创建一个 (3000, 4) 数组,最后一列是特定值。 I can do a very simple np.insert(x, 1, val, axis=1) to insert the value before column 1, but I can't add it to the last column with np.insert().我可以做一个非常简单的np.insert(x, 1, val, axis=1)在第 1 列之前插入值,但我不能用 np.insert() 将它添加到最后一列。 I can do np.repeat(val, np.shape(x)[0]) or using np.hstack() but they require creating an array first of the same length as the original array (which varies) and a bit clunky (maybe this is the only way), and I'm guessing there is a better way if I am only concerned with one value I want to append.我可以做np.repeat(val, np.shape(x)[0])或使用np.hstack()但他们需要首先创建一个与原始数组(不同)长度相同且有点笨重的数组(也许这是唯一的方法),如果我只关心一个我想要 append 的值,我猜有更好的方法。

Is there anything better than np.concatenate((x, np.repeat(val, np.shape(x)[0])[:, np.newaxis]), axis=1) ?有什么比np.concatenate((x, np.repeat(val, np.shape(x)[0])[:, np.newaxis]), axis=1)吗?

You can allocate a larger array, copy old values from x and fill the last column with a scalar with a little help of broadcasting您可以分配一个更大的数组,从 x 复制旧值并在广播的帮助下用标量填充最后一列

y=np.empty_like(x, shape=(3000,4))
y[:,:-1]=x
y[:,-1]=your_value

I would suggest using np.c_ and np.ones_like to cut out some verbosity, but the solution is similar to your suggestion我建议使用 np.c_ 和 np.ones_like 来减少一些冗长,但解决方案类似于您的建议

x=np.c_[x,val*np.ones_like(x[:,0])]

It doesn't require allocating memory for a new matrix.它不需要为新矩阵分配 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM