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
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.

🌐
NumPy
numpy.org › doc › stable › reference › arrays.scalars.html
Scalars — NumPy v2.4 Manual
These type descriptors are mostly ... with Python’s types. 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. Array scalars live in a hierarchy (see the Figure below) of data types. They can be detected using the hierarchy: For example, isinstance(val, ...
Discussions

terminology - What does it mean when data is scalar? - Software Engineering Stack Exchange
I don't know what scalar means exactly, but I'm trying to see if I'm thinking about it correctly. Does scalar relate to arbitrariness where the type of data could be any type, or a system is not ab... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
May 5, 2014
What are numpy scalars used for?
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. More on reddit.com
🌐 r/learnpython
4
7
November 1, 2023
Why do I keep getting runtimewarning: invalid value encountred in scalar power?
You need to format your code properly so we can see the indentation. The learnpython FAQ shows how. I've formatted your code to what you probably used: import random as rand import numpy as np # limits of integration a = 0 b = np.pi N = 1000 # array of zeros of length N ar = np.zeros(N) # iterating over each value of ar and #filling it with a random value between #the limits a and b for i in range (len(ar)): ar[i] = rand.uniform(a,b) # variable to store sum of the functions of # different values of x integral = 0.0 # function to calculate the (sinx)^(2/(x^2) of a particular # value of x def f(x): return np.sin(x)**(2/(x**2)) # itertes and sums up values of different functions # of x for i in ar: integral += f(i) ans = (b-a)/float(N)*integral print(format(ans)) When I run that code I get no error. I get results near 2. When asking a question you need to show us the real code, formatted properly and, if you get an error, show us the full error traceback formatted as code. This helps us to help you. More on reddit.com
🌐 r/learnpython
1
0
June 8, 2023
Created my first dataframe ever in Pandas, what is this scalar error?
A dataframe is a table structure. It doesn't make sense to have a column with a single value. That doesn't make a table. You can represent this kind of thing as a Pandas series, if you like. More on reddit.com
🌐 r/learnpython
6
1
April 17, 2023
🌐
SciPy
docs.scipy.org › doc › numpy-1.13.0 › reference › arrays.scalars.html
Scalars — NumPy v1.13 Manual
June 10, 2017 - These type descriptors are mostly ... with Python’s types. 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. Array scalars live in a hierarchy (see the Figure below) of data types. They can be detected using the hierarchy: For example, isinstance(val, ...
🌐
GeeksforGeeks
geeksforgeeks.org › numpy-isscalar-python
numpy.isscalar() in Python | GeeksforGeeks
January 2, 2024 - Here are several commonly used ... understanding. ... In this example Python program uses NumPy's `isscalar()` function to check if an input array `[1, 3, 5, 4]` is a scalar and prints the result....
🌐
OpenGenus
iq.opengenus.org › scalar-variable-types-in-python
Scalar Variable Types in Python
March 6, 2022 - You can call on this variable with the complex(a,b) function or just initiating a variable with the complex form, z = a + bj any letter other than j will produce an error. The code below shows an example of how to set up a complex variable. both will produce 4 + 3j when printed. ... The None type is a special Python type in which there is only one possible value and that is None.
🌐
UC Davis
web.cs.ucdavis.edu › ~koehl › Teaching › ECS15 › Lectures › Python_Chapter2.doc doc
Chapter 1: Scalar Variables and Data Types
Patrice Koehl Department of Computer Science Genome Center Room 4319, Genome Center, GBSF 451 East Health Sciences Drive University of California Davis, CA 95616 Phone: (530) 754 5121 koehl@cs.ucdavis.edu · Lecture Time and Location:
Find elsewhere
🌐
Quora
quora.com › What-is-difference-between-array-and-scalar-in-Python
What is difference between array and scalar in Python? - Quora
Answer: Briefly, a scalar is one variable - for example an integer. It can take different values at different times, but at any one time it only has one single value. An array is a set of variables - in most languages these all have to be of ...
🌐
Ucdavis
mae.engr.ucdavis.edu › dsouza › Classes › ECS15-W12 › PythonChapter1.pdf pdf
7 Chapter 1: Scalar Variables and Data Types 1. Python as a calculator
parentheses: (2+3)*4. These are exactly the rules used by Python. Some of the operators listed in the table above are unusual, and require more explanations: ... In the example given above, the variable k holds the remainder of the division of 52 by 3, i.e. 1. ... In this example, “a” takes successively the values 20, 24 and 8.
🌐
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.
🌐
Stata
stata.com › python › api16 › Scalar.html
Scalar (sfi.Scalar) — Python API documentation for Stata 16
Interval] -------------+---------------------------------------------------------------- weight | -.0065879 .0006371 -10.34 0.000 -.0078583 -.0053175 foreign | -1.650029 1.075994 -1.53 0.130 -3.7955 .4954422 _cons | 41.6797 2.165547 19.25 0.000 37.36172 45.99768 ------------------------------------------------------------------------------ >>> stata: ereturn list scalars: e(N) = 74 e(df_m) = 2 e(df_r) = 71 e(F) = 69.74846262000308 e(r2) = .6627029116028815 e(rmse) = 3.407059285651584 e(mss) = 1619.287698167387 e(rss) = 824.1717612920727 e(r2_a) = .6532015851691599 e(ll) = -194.1830643938065 e(
🌐
TutorialsPoint
tutorialspoint.com › home › articles on trending technologies › find the minimal data type of a scalar value in python
Find the minimal data type of a scalar value in Python
February 28, 2022 - print("Using the min_scalar() method ......",np.min_scalar_type(6.5e100)) # For scalar, returns the data type with the smallest size and smallest scalar kind which can hold its value....
🌐
Python Data Science Handbook
jakevdp.github.io › WhirlwindTourOfPython › 05-built-in-scalar-types.html
Built-In Types: Simple Values | A Whirlwind Tour of Python
For example: $$ 1 / 10 = 0.00011001100110011\cdots_2 $$ Just as decimal notation requires an infinite number of digits to perfectly represent $1/3$, binary notation requires an infinite number of digits to represent $1/10$. Python internally truncates these representations at 52 bits beyond the first nonzero bit on most systems. This rounding error for floating-point values is a necessary evil of working with floating-point numbers.
🌐
Pandas
pandas.pydata.org › docs › dev › reference › arrays.html
pandas arrays, scalars, and data types — pandas documentation
a PyArrow int64 will be returned as Python int, or NA for missing values. For more information, please see the PyArrow user guide. NumPy cannot natively represent timezone-aware datetimes. pandas supports this with the arrays.DatetimeArray extension array, which can hold timezone-naive or timezone-aware values. Timestamp, a subclass of datetime.datetime, is pandas’ scalar type for timezone-naive or timezone-aware datetime data.
🌐
Medium
medium.com › @jyotiranjanmishra1990 › all-you-need-to-know-about-different-data-types-in-python-a71d632897c7
All you need to know about different data types in Python | by Ranjan | Medium
July 30, 2021 - Python data types are mostly divided into two types, mutable and immutable. Immutable data types are mostly scalar types, except string. We can’t change the fundamental values.
🌐
UC Berkeley Statistics
stat.berkeley.edu › ~spector › extension › python › notes › node26.html
Conversion of Scalar Types
For example, consider the variable a, with a numeric value of 7, and the variable 'b' with the string value of ``8''. What should python do when you ask to ``add'' together these two values? >>> a = 7 >>> b = '8' >>> a + b Traceback (innermost last): File "<stdin>", line 1, in ?
🌐
CodeRivers
coderivers.org › blog › scalars-definition-python
Understanding Scalars in Python: Definitions, Usage, and Best Practices - CodeRivers
January 24, 2025 - For example, when converting a string to an integer, if the string does not represent a valid integer, a ValueError will be raised. You can use try - except blocks to handle such errors gracefully. try: str_num = 'abc' int_num = int(str_num) except ValueError: print("The string does not represent a valid integer.") Scalars are an essential part of Python programming.