如何在一列中创建一个1到n的2D数组,在另一列中创建零 - Python

时间:2021-03-13 09:17:35

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个1阵列。

2 个解决方案

#1


1  

Maybe something like this?

也许是这样的?

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

#2


0  

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. 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,). You should use np.column_stack as suggested by @Divakar.

顺便说一句,您的解决方案有两个问题。第一个是,错误地,连接的第二个参数是函数np.zeros而不是新创建的数组array_zeros。即使在解决了这个问题之后,第二个问题是两个数组将沿着它们的第零维连接,结果将是一个形状数组(200,)。您应该使用@Divakar建议的np.column_stack。

#1


1  

Maybe something like this?

也许是这样的?

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

#2


0  

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. 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,). You should use np.column_stack as suggested by @Divakar.

顺便说一句,您的解决方案有两个问题。第一个是,错误地,连接的第二个参数是函数np.zeros而不是新创建的数组array_zeros。即使在解决了这个问题之后,第二个问题是两个数组将沿着它们的第零维连接,结果将是一个形状数组(200,)。您应该使用@Divakar建议的np.column_stack。