Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of `numpy.array(value)`?

Tags:

numpy

numpy.array(value) evaluates to true, if value is int, float or complex. The result seems to be a shapeless array (numpy.array(value).shape returns ()).

Reshaping the above like so numpy.array(value).reshape(1) works fine and numpy.array(value).reshape(1).squeeze() reverses this and again results in a shapeless array.

What is the rationale behind this behavior? Which use-cases exist for this behaviour?

like image 522
fabianegli Avatar asked Jan 19 '26 18:01

fabianegli


1 Answers

When you create a zero-dimensional array like np.array(3), you get an object that behaves as an array in 99.99% of situations. You can inspect the basic properties:

>>> x = np.array(3)
>>> x
array(3)
>>> x.ndim
0
>>> x.shape
()
>>> x[None]
array([3])
>>> type(x)
numpy.ndarray
>>> x.dtype
dtype('int32')

So far so good. The logic behind this is simple: you can process any array-like object the same way, regardless of whether is it a number, list or array, just by wrapping it in a call to np.array.

One thing to keep in mind is that when you index an array, the index tuple must have ndim or fewer elements. So you can't do:

>>> x[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array

Instead, you have to use a zero-sized tuple (since x[] is invalid syntax):

>>> x[()]
3

You can also use the array as a scalar instead:

>>> y = x + 3
>>> y
6
>>> type(y)
numpy.int32

Adding two scalars produces a scalar instance of the dtype, not another array. That being said, you can use y from this example in exactly the same way you would x, 99.99% of the time, since dtypes inherit from ndarray. It does not matter that 3 is a Python int, since np.add will wrap it in an array regardless. y = x + x will yield identical results.

One difference between x and y in these examples is that x is not officially considered to be a scalar:

>>> np.isscalar(x)
False
>>> np.isscalar(y)
True

The indexing issue can potentially throw a monkey wrench in your plans to index any array like-object. You can easily get around it by supplying ndmin=1 as an argument to the constructor, or using a reshape:

>>> x1 = np.array(3, ndmin=1)
>>> x1
array([3])

>>> x2 = np.array(3).reshape(-1)
>>> x2
array([3])

I generally recommend the former method, as it requires no prior knowledge of the dimensionality of the input.

FurtherRreading:

  • Why are 0d arrays in Numpy not considered scalar?
like image 152
Mad Physicist Avatar answered Jan 22 '26 23:01

Mad Physicist



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!