Tony Tannous - 1 year ago 96

Python Question

I need to convert B to a 1-D array

I have a matrix which I am trying to turn to a 1-D array.

However I am getting an array with 1 cell which holds the 1-D array.

How do I fix it ?

Python CODE:

`import numpy as np`

def computecoreset():

a = np.matrix('1 2 19 22; 3 4 28 11')

B = a.ravel()

cal = np.random.choice(B, 3)

return cal

print(computecoreset())

However:

`B = [[ 1 2 19 22 3 4 28 11]]`

Which is not the same as

`[ 1 2 19 22 3 4 28 11]`

Thanks in advanced!

Answer Source

`a.ravel()`

being a method of `NumPy matrix`

would still keep it as a matrix and NumPy matrices can't be `1D`

. So, instead we can use `NumPy's ravel()`

method to convert into a flattened 1D NumPy array, like so -

```
np.ravel(a)
```

Sample run -

```
In [40]: a
Out[40]:
matrix([[ 1, 2, 19, 22],
[ 3, 4, 28, 11]])
In [41]: np.ravel(a)
Out[41]: array([ 1, 2, 19, 22, 3, 4, 28, 11])
```