PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 18, 2022

[FIXED] Why is np nan convertible to int by `astype` (but not by `int`)?

 July 18, 2022     integer, nan, numpy, python     No comments   

Issue

This question comes from a finding that is very much not intuitive to me. If one tries the following:

import numpy as np
print(np.array([np.nan]).astype(int))
print(int(np.array([np.nan])))

then the output of the first is [-9223372036854775808], and the second raises ValueError: cannot convert float NaN to integer. I'd expect the later behaviour, and I'd definitely not expect that one can convert np.nan to an int. Why is this like that? Why can one use astype to convert np.nan to int? Does it have any functionality or meaning?


Solution

.astype has optional argument casting whose default value is 'unsafe'. Following values are allowed

  • ‘no’ means the data types should not be cast at all.
  • ‘equiv’ means only byte-order changes are allowed.
  • ‘safe’ means only casts which can preserve values are allowed.
  • ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
  • ‘unsafe’ means any data conversions may be done.

When one attempt to do

import numpy as np
print(np.array([np.nan]).astype(int, casting="safe"))

one gets following error

TypeError: Cannot cast array from dtype('float64') to dtype('int32') according to the rule 'safe'


Answered By - Daweo
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing