Why is NaN considered a float?

B pandas, when we try to make a series containing values NaNfor an integer with a fragment, for example below

df.A = df.A.apply(int)I often see an error message

ValueError: cannot convert float NaN to integer

I understand that values NaNcannot be converted to integer. But I'm curious what was thrown in this case ValueError. he says that float NaN cannot be converted to integer.

Is there any specific reason why values ​​are NaNtreated as floating point objects? or is this the case of any problem displaying error messages?

+5
source share
2 answers

: IEEE 754 NaN float.

, pd.Series , pd.to_numeric . .

import pandas as pd
import numpy as np

s = pd.Series([1, 2.5, 3, 4, 5.5])        # s.dtype = float64
s = s.astype(float)                       # s.dtype = float64
s = pd.to_numeric(s, downcast='float')    # s.dtype = float32

t = pd.Series([1, np.nan, 3, 4, 5])       # s.dtype = float64
t = t.astype(int)                         # ValueError
t = pd.to_numeric(t, downcast='integer')  # s.dtype = float64

u = pd.Series([1, 2, 3, 4, 5, 6])         # s.dtype = int64
u = u.astype(int)                         # s.dtype = int32
u = pd.to_numeric(u, downcast='integer')  # s.dtype = int8
+5

, , "" a float. CPython float double C, , IEEE 754 .

, , ( , ).

, , "" .

  • : + ∞ -∞.
  • NaN: NaN (qNaN) NaN (sNaN).

float , :

nan = float('nan')
inf = float('inf')

int:

>>> int(nan)
ValueError: cannot convert float NaN to integer

>>> int(inf)
OverflowError: cannot convert float infinity to integer
+5

Source: https://habr.com/ru/post/1693020/


All Articles