-2

How can I create a 2-d array from 1-d array in python?

Example :

     i/p 1-D array : [3,4,6]

Result :

     o/p 2-D array : [[3,], [4,], [6,]]

Or lets say a dataframe column with values = [3,4,6] as the 2-d above mentioned array.

Thanks in advance.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149

2 Answers2

-1

You can create an array for each element:

array = [3,4,6]
array2 = [[x] for x in array]
print(array2)

Try it online!

Or use map():

array = [3,4,6]
array2 = list(map(lambda x: [x], array))
print(array2)

Try it online!

aloisdg
  • 22,270
  • 6
  • 85
  • 105
-1

You can use reshape to deal with numpy arrays. (Documentation)

Ex:

a = [1,2,3]
#reshaping a into 1 column and 3 rows
b = np.reshape(a,(3,1))

print(b)

to be more general you can just use the length of a as argument for the number of rows:

b = np.reshape(a,(len(a),1))

Note: As far as I know (someone correct me if I'm wrong), using numpy to deal with numpy arrays is faster. In other cases I suppose the list comprehension example would be the faster option.

Chicrala
  • 994
  • 12
  • 23