Reputation: 5
I get a python object, which has dimension (10, ). I want to change it to array with shape (10, 1).
For example:
x = np.random.normal(size=(10, 3))
x = x[:, 0]
x.shape
# which is (10, )
y = np.random.normal(size=(10, 1))
y.shape
# which is (10, 1)
z = x + y
z.shape
# which is (10, 10)
How can I accomplish this? plus, why does the z variable above get a (10, 10) shape?
Upvotes: 1
Views: 194
Reputation: 400
import numpy as np
x = np.random.normal(size=(10, 3))
x = np.array(x[:, 0])
x = np.reshape(x, (10, 1)) # this line added
x.shape
# which is (10, )
y = np.random.normal(size=(10, 1))
y.shape
# which is (10, 1)
z = x + y
z.shape
# which is (10, 10)
Upvotes: 0
Reputation: 30930
You don't need use numpy.array
x = x[:, 0]
is equal to x = np.array(x[:, 0])
you can indicate that you want an additional dimension and you do not give up explicitly indexing the first column:
x = np.random.normal(size=(10, 3))
x = x[:, 0, None]
x.shape
#(10, 1)
Or you can use it when you sum
x = np.random.normal(size=(10, 3))
y = np.random.normal(size=(10, 1))
#x[:, 0, None] + y
x = x[:, 0]
x[:, None] + y
We can also indicate that we want everything before the second column, this syntax is shorter but perhaps it is more readable 0
than :1
x = np.random.normal(size=(10, 3))
x = x[:, :1]
x.shape
#(10, 1)
we could also use additional methods.
np.expand_dims
x = np.random.normal(size=(10, 3))
x = np.expand_dims(x[:, 0], 1)
x.shape
#(10, 1)
np.reshape
x = np.random.normal(size=(10, 3))
x = x[:, 0].reshape(-1, 1)
x.shape
#(10, 1)
Here the -1
allows this to work with another number of rows different from 10
Upvotes: 0
Reputation: 1006
To change the shape you could add this piece of code-
np.reshape(x, (10,1))
Which would resize the x
to (10,1)
and return it
Upvotes: 1