1

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?

1
  • So how far have you gotten in your numpy introduction? Changing array shape should be in chapter one, two at the latest. Adding two arrays, and broadcasting rules, should be part of the intro as well. numpy.org/devdocs/user/quickstart.html Commented May 3, 2020 at 6:50

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

really specifying 10 could be an error, here we can use -1
0

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

Comments

0
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)

1 Comment

really specifying 10 could be an error, here we can use -1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.