Reputation: 1576
Not to be confused with the inverse task, that is covered plenty.
I am looking for something like np.dtype(7.7) == np.float
.
The motivation is to be able to handle any array-like input just like numpy itself. To construct the output or temporary data, I sometimes want to use the input type if possible.
Edit: Maybe that was a bad (too specific) example; I know that np.float
happens to be just an alias for the builtin float
. I was thinking more along the following lines.
myInput = something
# required to have a homogeneous data type in the documentation of my function;
# maybe constrained to float, int, string, lists of same length and type
# but I would like to handle simply as much of that as numpy can handle
numInput = len(myInput)
numOutput = numInput // 2 # just for example
myOutput = np.empty(shape=(numOutput), dtype=???)
for i in range(numOutput):
myOutput[i] = whatever # maybe just a copy, hence the same data type
Upvotes: 1
Views: 1666
Reputation: 63
You could simply use np.float64(original_float), or whatever numpy type you wish to convert your variable to.
For the record, this code works:
val = 7.7
if isinstance(val, float) is True:
val = np.float64(val)
if isinstance(val, np.float64) is True:
print("Success!")
>>>Success!
Hope this helps.
Edit: I just saw @user2357112 supports Monica's comment to your question and it's important to note that effectively np.float acts the same way as float. The implementation I provided is oriented towards special numpy types like np.float32 or np.float64, the one I used in the test code. But if I performed the same test with just np.float this would be the result:
val = 7.7
if isinstance(val, float) is True:
if isinstance(val, np.float) is True:
print("Success!")
>>>Success!
Thus proving that from the interpreter's point of view float and np.float are pretty much the same type.
Upvotes: 0
Reputation: 280237
numpy.float
is just the regular Python float
type. It's not a NumPy dtype. It's almost certainly not what you need:
>>> import numpy
>>> numpy.float is float
True
If you want the dtype NumPy would coerce your scalar to, just make an array and get its dtype:
>>> numpy.array(7.7).dtype
dtype('float64')
If you want the type NumPy uses for scalars of this dtype, access the dtype's type
attribute:
>>> numpy.array(7.7).dtype.type
<class 'numpy.float64'>
Upvotes: 2