Vishruth Subramanian
Vishruth Subramanian

Reputation: 141

Convert List into Numpy 2D Array

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)

Upvotes: 0

Views: 1073

Answers (3)

mathfux
mathfux

Reputation: 5949

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

Upvotes: 2

Ehsan
Ehsan

Reputation: 12417

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]]

Upvotes: 4

wprazuch
wprazuch

Reputation: 101

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)

Upvotes: 0

Related Questions