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 OverflowType 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'
str is able to convert any type into string. It can be numpy.array / list / float
# using numpy array
new_array = numpy.array([1,2,3])
str(new_array)
>> '[1 2 3]'
# using list
new_list = [1, 2, 3]
str(new_list)
>> '[1, 2, 3]'
# using float
new_float = 1.1
str(new_float)
>> '1.1'
How to convert python int into numpy.int64? - Stack Overflow
How to convert python int into numpy.int64?
TypeError: must be str, not numpy.int64
python - Tensorflow TypeError: Can't convert 'numpy.int64' object to str implicitly - Stack Overflow
z_as_int64 = numpy.int64(z)
It's that simple. Make sure you have a good reason, though - there are a few good reasons to do this, but most of the time, you can just use a regular int directly.
import numpy as np
z = 3
z = np.dtype('int64').type(z)
print(type(z))
outputs:
<class 'numpy.int64'>
But i support Juliens question in his comment.
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
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!
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().
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.
Solution was:
import pandas as pd
ts = pd.to_datetime(str(date))
d = ts.strftime('%Y.%m.%d')
You can use Numpy's datetime_as_string function. The unit='D' argument specifies the precision, in this case days.
>>> t = numpy.datetime64('2012-06-30T20:00:00.000000000-0400')
>>> numpy.datetime_as_string(t, unit='D')
'2012-07-01'