简体   繁体   English

如何创建一个二维数组,其中一列为1到n,另一列为零-Python

[英]How can I create a 2D array with 1 to n in one column and zeros in the other - Python

I tried creating two arrays and then adding them together 我尝试创建两个数组,然后将它们加在一起

array_nmax = np.arange (100)
array_zeros = np.zeros (100, dtype = np.int)
array_final = np.append (array_nmax,np.zeros, axis = 0)

but it says that they're not the same dimensions even though they should be both 100 by 1 arrays. 但它说它们的尺寸并不相同,即使它们都应为100 x 1阵列。

Maybe something like this? 也许是这样的吗?

a = np.zeros((100, 10), dtype=np.int)
a[:, 0] = np.arange(0, 100)

Slower than @GrigorisG's answer and not so readable, but still a possible solution: 比@GrigorisG的答案慢,虽然不太可读,但仍然是可能的解决方案:

np.arange(100)[:,None] * [1,0]

By the way, there are two problems in your solution. 顺便说一句,您的解决方案中有两个问题。 The first one is that, by mistake, the second argument to concatenate is the function np.zeros instead of the newly created array array_zeros . 第一个错误是, concatenate的第二个参数是函数np.zeros而不是新创建的数组array_zeros Even after fixing this, the second problem is that the two arrays will be concatenated along their zero-th dimension and the result will be an array of shape (200,) . 即使解决了这个问题,第二个问题是两个数组将沿着它们的第零维连接在一起,结果将是形状数组(200,) You should use np.column_stack as suggested by @Divakar. 您应该np.column_stack建议使用np.column_stack。

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

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