0

How to convert a list into a numpy 2D ndarray. For example:

lst = [20, 30, 40, 50, 60]

Expected result:

>> print(arr)
>> array([[20],
       [30],
       [40],
       [50],
       [60]])

>> print(arr.shape)
>> (5, 1)
3
  • 2
    [[i] for i in x] or np.reshape([20, 30, 40, 50, 60], (-1,1)) ? Commented Aug 14, 2020 at 14:58
  • @Yoshi thanks for the suggestion but that doesn't quite seem to help me :( Commented Aug 14, 2020 at 15:00
  • I just missreaded the question. @Sushanth answer is what I think you are looking for :) Commented Aug 14, 2020 at 15:00

3 Answers 3

4

Convert it to array and reshape:

x = np.array(x).reshape(-1,1)

reshape adds the column structure. The -1 in reshape takes care of the correct number of rows it requires to reshape.

output:

[[20]
 [30]
 [40]
 [50]
 [60]]
Sign up to request clarification or add additional context in comments.

Comments

2

If you need your calculations more effective, use numpy arrays instead of list comprehensions. This is an alternative way using array broadcasting

x = [20, 30, 40, 50, 60]
x = np.array(x) #convert your list to numpy array
result = x[:, None] #use numpy broadcasting

if you still need a list type at the end, you can convert your result efficiently using result.tolist()

1 Comment

That's not broadcasting. It's just indexing. None is an alias for np.newaxis
0

You may use a list comprehension and then convert it to numpy array:

import numpy as np

x = [20, 30, 40, 50, 60]

x_nested = [[item] for item in x]

x_numpy = np.array(x_nested)

1 Comment

This is a much less efficient technique. When dealing with numerical data, get it into numpy as fast as possible, then manipulate it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.