-
-
Notifications
You must be signed in to change notification settings - Fork 9.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
BUG: np.can_cast fails with string input #22977
Comments
In all examples of the doc of np.can_cast, from_input can only be datatype、scalar or array scalar I think it's an ENH but not a bug. |
But strings are scalars in numpy according to https://numpy.org/doc/stable/reference/generated/numpy.isscalar.html |
- np.can_cast will fail with strings instead of returning false numpy issue: numpy/numpy#22977
It's possible that the author meant numerical scalar, although I can see the use of being able to check if a string can be casted to a numerical type. |
It is what it is. I suspect the only good solution would be to add a new function |
Describe the issue:
The
can_cast
function fails with a rather non-descriptive error iffrom_
is a string (Or 'None'-descriptive? SCNR).Since strings are scalars in numpy, I would expect this to return False if comparing to a non-string dtype.
Although on the other hand:
works just fine, so maybe one would expect it to return
True
in some cases as well.Reproduce the code example:
Error message:
Runtime information:
sys.version:
'3.9.15 | packaged by conda-forge | (main, Nov 22 2022, 15:55:03) \n[GCC 10.4.0]'
np.version:
'1.23.5'
Context for the issue:
I want to convert inputs to the expected dtypes.
My plan was to use
np.can_cast(input_value, expected_dtype, casting="safe")
to test if the values are valid and can be casted without loss of precision.I could of course compare the dtypes directly as well and only cast to strictly larger types.
The advantage in this solution for me was that it would check whether the python integers and floats fit into the dtype:
np.can_cast(42.0, np.float32)
isTrue
, whereasnp.can_cast(type(42.0), np.float32)
returnsFalse
, because python floats are 64-bit and in general the conversion will be lossy.The text was updated successfully, but these errors were encountered: