A NumPy scalar is any object which is an instance of np.generic or whose type is in np.ScalarType:

In [12]: np.ScalarType
Out[13]:
(int,
 float,
 complex,
 long,
 bool,
 str,
 unicode,
 buffer,
 numpy.int16,
 numpy.float16,
 numpy.int8,
 numpy.uint64,
 numpy.complex192,
 numpy.void,
 numpy.uint32,
 numpy.complex128,
 numpy.unicode_,
 numpy.uint32,
 numpy.complex64,
 numpy.string_,
 numpy.uint16,
 numpy.timedelta64,
 numpy.bool_,
 numpy.uint8,
 numpy.datetime64,
 numpy.object_,
 numpy.int64,
 numpy.float96,
 numpy.int32,
 numpy.float64,
 numpy.int32,
 numpy.float32)

This definition comes from looking at the source code for np.isscalar:

def isscalar(num):
    if isinstance(num, generic):
        return True
    else:
        return type(num) in ScalarType

Note that you can test if something is a scalar by using np.isscalar:

>>> np.isscalar(3.1)
True

>>> np.isscalar([3.1])
False

>>> np.isscalar(False)
True

How do we know what we know?

I like learning how people know what they know—more than the answers themselves. So let me try to explain where the above answer comes from.

Having the right tools can help you figure out things like this for yourself.

I found this out by using IPython. Using its TAB-completion feature, typing

In [19]: import numpy as np
In [20]: np.[TAB]

causes IPython to display all variables in the np module namespace. A search for the string "scalar" will lead you to np.ScalarType and np.isscalar. Typing

In [20]: np.isscalar?

(note the question mark at the end) prompts IPython to show you where np.isscalar is defined:

File:  /data1/unutbu/.virtualenvs/dev/lib/python2.7/site-packages/numpy/core/numeric.py

which is how I got to the definition of isscalar. Alternatively, the NumPy documentation for isscalar has a link to the source code as well.

Answer from unutbu on Stack Overflow
🌐
NumPy
numpy.org › doc › stable › reference › arrays.scalars.html
Scalars — NumPy v2.4 Manual
Thus, for example isinstance(val, np.complexfloating) will return True if val is a complex valued type, while isinstance(val, np.flexible) will return true if val is one of the flexible itemsize array types (str_, bytes_, void). Figure: Hierarchy of type objects representing the array data types. Not shown are the two integer types intp and uintp which are used for indexing (the same as the default integer since NumPy 2).# ... However, array scalars are immutable, so none of the array scalar attributes are settable.
Top answer
1 of 4
54

A NumPy scalar is any object which is an instance of np.generic or whose type is in np.ScalarType:

In [12]: np.ScalarType
Out[13]:
(int,
 float,
 complex,
 long,
 bool,
 str,
 unicode,
 buffer,
 numpy.int16,
 numpy.float16,
 numpy.int8,
 numpy.uint64,
 numpy.complex192,
 numpy.void,
 numpy.uint32,
 numpy.complex128,
 numpy.unicode_,
 numpy.uint32,
 numpy.complex64,
 numpy.string_,
 numpy.uint16,
 numpy.timedelta64,
 numpy.bool_,
 numpy.uint8,
 numpy.datetime64,
 numpy.object_,
 numpy.int64,
 numpy.float96,
 numpy.int32,
 numpy.float64,
 numpy.int32,
 numpy.float32)

This definition comes from looking at the source code for np.isscalar:

def isscalar(num):
    if isinstance(num, generic):
        return True
    else:
        return type(num) in ScalarType

Note that you can test if something is a scalar by using np.isscalar:

>>> np.isscalar(3.1)
True

>>> np.isscalar([3.1])
False

>>> np.isscalar(False)
True

How do we know what we know?

I like learning how people know what they know—more than the answers themselves. So let me try to explain where the above answer comes from.

Having the right tools can help you figure out things like this for yourself.

I found this out by using IPython. Using its TAB-completion feature, typing

In [19]: import numpy as np
In [20]: np.[TAB]

causes IPython to display all variables in the np module namespace. A search for the string "scalar" will lead you to np.ScalarType and np.isscalar. Typing

In [20]: np.isscalar?

(note the question mark at the end) prompts IPython to show you where np.isscalar is defined:

File:  /data1/unutbu/.virtualenvs/dev/lib/python2.7/site-packages/numpy/core/numeric.py

which is how I got to the definition of isscalar. Alternatively, the NumPy documentation for isscalar has a link to the source code as well.

2 of 4
14

In this context, a scalar is one of the things you put in an array. A single 64-bit float or 32-bit int, for example, rather than a whole array of them.

🌐
Reddit
reddit.com › r/learnpython › what are numpy scalars used for?
r/learnpython on Reddit: What are numpy scalars used for?
November 1, 2023 -

Am I correct in treating scalars as souped-up versions of 'standard' Python data types (+ some new data types not in base Python), which happen to have the same attributes and methods that ndarrays have, even though many of such attributes/methods are meaningless to scalars?

The one part that confuses me a lot on the document is the term "array scalars". What does the word array have to do with the scalar?

https://numpy.org/doc/stable/reference/arrays.scalars.html

Top answer
1 of 3
5
Its just a misuse of terminology carried over from MATLAB. In MATLAB, everything is an array, including values you would usually think of as scalars: 1 == [ 1 ] "string" == [ "string" ] '' == char([]) "" == [ "" ] ~= string([]) Notice especially the last line. The empty string scalar "" is not the same thing as an empty array of strings string([]). NumPy copies this idea of everything being an array for vectorized operations and broadcasting purposes. Scalars are just arrays with a single element.
2 of 3
2
The link is talking about datatypes. A scalar is a single value, in this context it is talking about a single datatype that is broadcast across an array hence the term array scalar. numpy has its own versions of builtins datatypes. Many of these inherit from the builtins datatype however some of the datatypes that are not inheritable such as bool or are not a fixed width int are essentially reimplemented in numpy. The following is essentially equivalent to bool: np.bool The following is essentially equivalent to int: np.int32 == np.int_ The following is essentially equivalent to float: np.float64 == np.float_ The following is essentially equivalent to complex: np.complex128 == np.complex_ The following is essentially equivalent to str: np.str_ The following is essentially equivalent to bytes: np.bytes_ The following is essentially equivalent to datetime.datetime: np.datetime64_ The following is essentially equivalent to datetime.timedelta: np.timedelta64_ The 32 bit (4 bytes), 64 bit (8 bytes) and 128 bit (16 bytes) are the number of bits occupied by the datatype. For the int there are numerous signed (_ and +) and unsigned (+ only) datatypes that usually use less memory but have a smaller dynamic range. They are used in some applications to conserve memory/be slightly more efficient. For example an integer array may be used to represent the brightness value of each pixel on a screen. Since the hardware of the screen only supports 256 values ranging from 0:256 (inclusive of 0 and exclusive of 256), using np.int32 by default will consume more memory than required and therefore using np.uint8 will be more appropriate. If numpy is imported: import numpy as np And an array is produced using: arr1 = np.array([1, 2, 3]) arr2 = np.array([1., 2, 3]) arr3 = np.array([1, 2, 3], dtype=np.float64) arr4 = np.array([1, 2, 3], dtype=float) The datatype will be automatically be determined from the data in the list unless explicitly implied: arr1.dtype arr2.dtype arr3.dtype arr4.dtype will return 'int32','float64','float64' and 'float64' respectively. Notice when the builtins float is specified that the numpy equivalent np.float64 is selected.
🌐
NumPy
numpy.org › doc › 2.3 › reference › arrays.scalars.html
Scalars — NumPy v2.3 Manual
Thus, for example isinstance(val, np.complexfloating) will return True if val is a complex valued type, while isinstance(val, np.flexible) will return true if val is one of the flexible itemsize array types (str_, bytes_, void). Figure: Hierarchy of type objects representing the array data types. Not shown are the two integer types intp and uintp which are used for indexing (the same as the default integer since NumPy 2).# ... However, array scalars are immutable, so none of the array scalar attributes are settable.
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-isscalar-python
numpy.isscalar() in Python - GeeksforGeeks
January 2, 2024 - The `numpy.isscalar()` is a function in the NumPy library of Python that is used to determine whether a given input is a scalar or not. A scalar is a single value, as opposed to an array or a more complex data structure. The function returns ...
🌐
Finxter
blog.finxter.com › 5-best-ways-to-convert-a-python-numpy-array-to-a-scalar-value
5 Best Ways to Convert a Python NumPy Array to a Scalar Value – Be on the Right Side of Change
February 20, 2024 - This method effectively reduces the dimensionality from an array to a scalar value. A universal approach for getting the scalar is casting the one-element array to its respective type using int() or float() Python’s built-in functions. This is quick and efficient for converting elements to standard Python types. ... import numpy as np # Create a one-element numpy array array = np.array([42]) # Convert to scalar value = int(array) print(value)
Find elsewhere
🌐
SciPy
docs.scipy.org › doc › numpy-1.13.0 › reference › arrays.scalars.html
Scalars — NumPy v1.13 Manual
June 10, 2017 - Array scalars have the same attributes and methods as ndarrays. [1] This allows one to treat items of an array partly on the same footing as arrays, smoothing out rough edges that result when mixing scalar and array operations.
🌐
NumPy
numpy.org › doc › 1.17 › reference › arrays.scalars.html
Scalars — NumPy v1.17 Manual
February 18, 2020 - The bool_ data type is very similar to the Python BooleanType but does not inherit from it because Python’s BooleanType does not allow itself to be inherited from, and on the C-level the size of the actual bool data is not the same as a Python Boolean scalar. ... The bool_ type is not a subclass of the int_ type (the bool_ is not even a number type). This is different than Python’s default implementation of bool as a sub-class of int. ... The int_ type does not inherit from the int built-in under Python 3, because type int is no longer a fixed-width integer type. ... The default data type in NumPy is float_.
🌐
NumPy
numpy.org › devdocs › reference › arrays.scalars.html
Scalars — NumPy v2.5.dev0 Manual
Thus, for example isinstance(val, np.complexfloating) will return True if val is a complex valued type, while isinstance(val, np.flexible) will return true if val is one of the flexible itemsize array types (str_, bytes_, void). Figure: Hierarchy of type objects representing the array data types. Not shown are the two integer types intp and uintp which are used for indexing (the same as the default integer since NumPy 2).# ... However, array scalars are immutable, so none of the array scalar attributes are settable.
🌐
NumPy
numpy.org › doc › 2.1 › reference › arrays.scalars.html
Scalars — NumPy v2.1 Manual
Thus, for example isinstance(val, np.complexfloating) will return True if val is a complex valued type, while isinstance(val, np.flexible) will return true if val is one of the flexible itemsize array types (str_, bytes_, void). Figure: Hierarchy of type objects representing the array data types. Not shown are the two integer types intp and uintp which are used for indexing (the same as the default integer since NumPy 2).# ... However, array scalars are immutable, so none of the array scalar attributes are settable.
🌐
Studyopedia
studyopedia.com › home › scalar operations on numpy arrays
Scalar operations on Numpy arrays - Studyopedia
October 18, 2023 - Scalar operations on Numpy arrays include performing addition or subtraction, or multiplication on each element of a Numpy array. Let us see the following examples: ... The Addition Operation is adding a value to each element of a NumPy array.
🌐
Enqueuezero
enqueuezero.com › projects › numpy › scalar.html
The Scalar In NumPy | Enqueue Zero
In NumPy, a scalar is any object that you put in an array. It's similar to the concept in linear algebra, an element of a field which is used to define a vector space. NumPy ensures all scalars in an array have same types. It's impossible one scalar having type int32, the other scalars having ...
🌐
JAX Documentation
docs.jax.dev › en › latest › _autosummary › jax.numpy.isscalar.html
jax.numpy.isscalar — JAX documentation
JAX and NumPy differ in their representation of scalar values. NumPy has special scalar objects (e.g. np.int32(0)) which are distinct from zero-dimensional arrays (e.g.
🌐
NumPy
numpy.org › neps › nep-0051-scalar-representation.html
NEP 51 — Changing the representation of NumPy scalars — NumPy Enhancement Proposals
These differences will be exacerbated when adopting NEP 50 because the lower precision NumPy scalar will be preserved more often. Even np.float64, which is very similar to Python’s float and inherits from it, does behave differently for example when dividing by zero. Another common source of confusion are the NumPy booleans. Python programmers sometimes write obj is True and will surprised when an object that shows as True fails to pass the test. It is much easier to understand this behavior when the value is shown as np.True_.
🌐
GeeksforGeeks
geeksforgeeks.org › numpy-asscalar-in-python
numpy.asscalar() in Python | GeeksforGeeks
November 28, 2018 - numpy.asscalar() function is used when we want to convert an array of size 1 to its scalar equivalent.