Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i convert the entries within an array into arrays in python?

Tags:

python

numpy

I need to convert a numpy array as follows:

[1,1,1,1] -> [[1],[1],[1],[1]]
like image 285
alexthegreat Avatar asked Apr 10 '26 18:04

alexthegreat


1 Answers

Use np.reshape:

import numpy as np

values = np.random.randint(1, 10, 10)
print(values)
values = values.reshape((-1, 1))
print(values)
# Before reshaping
[5 9 8 1 2 6 2 2 9 8]

# After reshaping
[[5]
 [9]
 [8]
 [1]
 [2]
 [6]
 [2]
 [2]
 [9]
 [8]]

Using -1 tells NumPy that the new shape should be compatible with the original shape (i.e. it should figure out the value for that dimension based on the number of elements in the array).

like image 169
azro Avatar answered Apr 13 '26 08:04

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!