alvas - 4 months ago 69

Python Question

I can't seem to convert it into an

`ndarray`

`ndarray`

*

`array`

I have a list of integer counts like this

`[[1, 2, 4, 1, 5],`

[6, 0, 0, 0, 2],

[0, 0, 0, 1, 0]]

And i manage to use this code to create a

`np.array`

`import numpy as np`

x = [[1, 2, 4, 1, 5],

[6, 0, 0, 0, 2],

[0, 0, 0, 1, 0]]

print np.array(x)

[out]:

`[[1 2 4 1 5]`

[6 0 0 0 2]

[0 0 0 1 0]]

But I can't change it into a

`np.ndarray`

`import numpy as np`

x = [[1, 2, 4, 1, 5],

[6, 0, 0, 0, 2],

[0, 0, 0, 1, 0]]

print np.ndarray(x)

I got an error:

`Traceback (most recent call last):`

File "/home/alvas/workspace/sklearntut/test.py", line 7, in <module>

print np.ndarray(x)

TypeError: an integer is required

Answer Source

An `ndarray`

*is* a NumPy array.

```
>>> x = np.array([1, 2, 3])
>>> type(x)
<type 'numpy.ndarray'>
```

The difference between `np.ndarray`

and `np.array`

is that the former is the actual type, while the latter is a flexible shorthand function for constructing arrays from data in other formats. The `TypeError`

comes your use of `np.array`

arguments to `np.ndarray`

, which takes completely different arguments (see docstrings).