0

Create an array with numpy and add elements to it. After you do this, print out all its elements on new lines.

I used the reshape function instead of a for loop. However, I know this would create problems in the long run if I changed my array values.

import numpy as np

a = np.array([0,5,69,5,1])

print(a.reshape(5,1))

How can I make this better? I think a for loop would be best in the long run but how would I implement it?

2 Answers 2

2

Some options to print an array "vertically" are:

  1. print(a.reshape(-1, 1)) - You can pass -1 as one dimension, meaning "expand this dimension to the needed extent".

  2. print(np.expand_dims(a, axis=1)) - Add an extra dimension, at the second place, so that each row will have a single item. Then print.

  3. print(a[:, None]) - Yet another way of reshaping the array.

Or if you want to print just elements of a 1-D array in a column, without any surrounding brackets, run just:

for x in a:
    print(x)
Sign up to request clarification or add additional context in comments.

Comments

0

You could do this:

print(a.reshape([a.shape[0], 1]))

This will work regardless of how many numbers are in your numpy array.

Alternatively, you could also do this:

[print(number) for number in a.tolist()]

1 Comment

If you want to change from a row array to a column array better use a.reshape(-1,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.