Type checking is not the only option to do what you want, but definitely one of the easiest:

import numpy as np

def to_str(var):
    if type(var) is list:
        return str(var)[1:-1] # list
    if type(var) is np.ndarray:
        try:
            return str(list(var[0]))[1:-1] # numpy 1D array
        except TypeError:
            return str(list(var))[1:-1] # numpy sequence
    return str(var) # everything else

EDIT: Another easy way, which does not use type checking (thanks to jtaylor for giving me that idea), is to convert everything into the same type (np.array) and then convert it to a string:

import numpy as np

def to_str(var):
    return str(list(np.reshape(np.asarray(var), (1, np.size(var)))[0]))[1:-1]

Example use (both methods give same results):

>>> to_str(1.) #float
'1.0'
>>> to_str([1., 1., 1.]) #list
'1.0, 1.0, 1.0'
>>> to_str(np.ones((1,3))) #np.array
'1.0, 1.0, 1.0'
Answer from dwitvliet on Stack Overflow
Discussions

How to convert python int into numpy.int64? - Stack Overflow
Given a variable in python of type int, e.g. z = 50 type(z) ## outputs is there a straightforward way to convert this variable into numpy.int64? It appears one would have to More on stackoverflow.com
🌐 stackoverflow.com
How to convert python int into numpy.int64?
new_variable = numpy.int64(z) But why would you want that? There is no advantage to using a numpy type outside of an array. More on reddit.com
🌐 r/learnpython
2
1
October 11, 2017
TypeError: must be str, not numpy.int64
You can not mix strings with integers, try converting the integer to a string with str([your variable here]) More on reddit.com
🌐 r/learnprogramming
3
3
October 30, 2019
python - Tensorflow TypeError: Can't convert 'numpy.int64' object to str implicitly - Stack Overflow
now that I've called numpy every int is a int64 and it seems that tensorflow try to convert very simply an int to string. More on stackoverflow.com
🌐 stackoverflow.com
🌐
NumPy
numpy.org › doc › stable › user › basics.types.html
Data types — NumPy v2.4 Manual
In addition to numerical types, NumPy also supports storing unicode strings, via the numpy.str_ dtype (U character code), null-terminated byte sequences via numpy.bytes_ (S character code), and arbitrary byte sequences, via numpy.void (V character code).
🌐
LinuxTut
linuxtut.com › en › 2253e32c22e81e688ef4
Convert numpy int64 to python int
October 24, 2020 - Convert numpy int64 to python int · [python] Convert date to string · [Python] Convert list to Pandas [Pandas] Convert Scratch project to Python · [Python] Convert Shift_JIS to UTF-8 · Convert python 3.x code to python 2.x · Convert NumPy array "ndarray" to lilt in Python [tolist ()] Convert elements of numpy array from float to int ·
🌐
Nabble
numpy-discussion.10968.n7.nabble.com › convert-to-string-astype-str-td26939.html
Numpy-discussion - convert to string - astype(str)
September 6, 2012 - Numpy-discussion · convert to string - astype(str) · Locked 3 messages · josef.pktd · Reply | Threaded · Open this post in threaded view · Travis Oliphant-6
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › how to convert python int into numpy.int64?
r/learnpython on Reddit: How to convert python int into numpy.int64?
October 11, 2017 -

Given a variable in python of type int, e.g.

z = 50
type(z) 
## outputs <class 'int'>

is there a straightforward way to convert this variable into numpy.int64?

It appears one would have to convert this variable into a numpy array, and then convert this into int64. That feels quite convoluted.

https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html

🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.fromstring.html
numpy.fromstring — NumPy v2.4 Manual
June 22, 2021 - This mode interprets string as ... frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using utf-8, which will not produce sane results. ... Reference object to allow the creation of arrays which are ...
🌐
NumPy
numpy.org › devdocs › user › basics.types.html
Data types — NumPy v2.5.dev0 Manual
In addition to numerical types, NumPy also supports storing unicode strings, via the numpy.str_ dtype (U character code), null-terminated byte sequences via numpy.bytes_ (S character code), and arbitrary byte sequences, via numpy.void (V character code).
🌐
AskPython
askpython.com › home › python string to float, float to string
Python String to float, float to String - AskPython
February 16, 2023 - List Comprehension can be used to convert Python NumPy float array to an array of String elements.
🌐
NumPy
numpy.org › doc › 2.1 › user › basics.types.html
Data types — NumPy v2.1 Manual
In addition to numerical types, NumPy also supports storing unicode strings, via the numpy.str_ dtype (U character code), null-terminated byte sequences via numpy.bytes_ (S character code), and arbitrary byte sequences, via numpy.void (V character code).
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.array2string.html
numpy.array2string — NumPy v2.4 Manual
Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: ... Total number of array elements which trigger summarization rather than full repr.
🌐
Reddit
reddit.com › r/learnprogramming › typeerror: must be str, not numpy.int64
r/learnprogramming on Reddit: TypeError: must be str, not numpy.int64
October 30, 2019 -

Hi, I am coding an experiment using the software Psycopy (using Python) and I keep getting the above error for the following code:

if trial_type == 'new_break':
full_path = 'typicality_images/' + corr_type + con_curr + '_break'
else:
full_path = 'learning_images/' + corr_type + con_curr + '/'

I read somewhere that I have to change the + to "," but that wasn't working either. Any help is appreciated! Thanks!

Top answer
1 of 13
573

Use val.item() to convert most NumPy values to a native Python type:

import numpy as np

# for example, numpy.float32 -> python float
val = np.float32(0)
pyval = val.item()
print(type(pyval))         # <class 'float'>

# and similar...
type(np.float64(0).item()) # <class 'float'>
type(np.uint32(0).item())  # <class 'int'>
type(np.int16(0).item())   # <class 'int'>
type(np.cfloat(0).item())  # <class 'complex'>
type(np.datetime64(0, 'D').item())  # <class 'datetime.date'>
type(np.datetime64('2001-01-01 00:00:00').item())  # <class 'datetime.datetime'>
type(np.timedelta64(0, 'D').item()) # <class 'datetime.timedelta'>
...

(A related method np.asscalar(val) was deprecated with 1.16, and removed with 1.23).


For the curious, to build a table of conversions of NumPy array scalars for your system:

for name in dir(np):
    obj = getattr(np, name)
    if hasattr(obj, 'dtype'):
        try:
            if 'time' in name:
                npn = obj(0, 'D')
            else:
                npn = obj(0)
            nat = npn.item()
            print('{0} ({1!r}) -> {2}'.format(name, npn.dtype.char, type(nat)))
        except:
            pass

There are a few NumPy types that have no native Python equivalent on some systems, including: clongdouble, clongfloat, complex192, complex256, float128, longcomplex, longdouble and longfloat. These need to be converted to their nearest NumPy equivalent before using .item().

2 of 13
45

If you want to convert (numpy.array OR numpy scalar OR native type OR numpy.darray) TO native type you can simply do :

converted_value = getattr(value, "tolist", lambda: value)()

tolist will convert your scalar or array to python native type. The default lambda function takes care of the case where value is already native.

🌐
GitHub
gist.github.com › tkf › 2276773
Character <-> Int conversion in numpy · GitHub
>>> au_as_int.view('U1') #doctest: +NORMALIZE_WHITESPACE array([u'A', u'B', u'C'], dtype='<U1') >>> # you can't do this >>> ac_as_int.view('U1') #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: new type not compatible with array. >>> # you need explicit conversion >>> ac_as_int.astype(numpy.uint32).view('U1') #doctest: +NORMALIZE_WHITESPACE array([u'A', u'B', u'C'], dtype='<U1')
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.ndarray.astype.html
numpy.ndarray.astype — NumPy v2.1 Manual
Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.