慕碼人2483693
2023-01-04 10:10:18
我需要一個包含不同數(shù)據(jù)類型(浮點數(shù)或整數(shù))列的表。我使用 dtype 來定義它們:import numpy as np# define arraydatadef=[ ('i', '<i4'), ('f', '<f8'), ('g', '<f8'), ('j', '<i4') ]arr = np.full((4,), np.nan, dtype=datadef) # fill array with dataarr['i'] = np.array([1, 2, 3, 4])arr['f'] = np.array([1.3333333333, np.nan, 2.6666666666666666, 5.0])arr['g'] = np.array([2.77777777777, 5.4, 3.4, np.nan])# nothing for 'j'print arr輸出 :[(1, 1.33333333, 2.77777778, -2147483648) (2, nan, 5.4 , -2147483648) (3, 2.66666667, 3.4 , -2147483648) (4, 5. , nan, -2147483648)]最后一列的NaN值已轉(zhuǎn)換為-2147483648,到目前為止沒有問題。但是現(xiàn)在我無法檢查我的數(shù)組中的值是否確實是 NaN :row = arr[1]print np.isnan(row) # TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''在單個單元格上,信息似乎NaN丟失了,-2147483648被認為是“經(jīng)典數(shù)字”:print row # (2, nan, 5.4, -2147483648)print np.isnan(row[0]) # False, OKprint np.isnan(row[1]) # True, OKprint np.isnan(row[3]) # False, expected True在這種情況下是否有一種簡單的方法來檢查NaN整數(shù)?
1 回答

青春有我
TA貢獻1784條經(jīng)驗 獲得超8個贊
np.nan是浮點數(shù)而不是整數(shù)。您要么必須更改最后一列的數(shù)據(jù)類型,要么使用不同的結(jié)構(gòu)將 nan 存儲為整數(shù)。
datadef=[ ('i', '<i4'), ('f', '<f8'), ('g', '<f8'), ('j', '<f4') ]
arr = np.full((4,), np.nan, dtype=datadef)
# fill array with data
arr['i'] = np.array([1, 2, 3, 4])
arr['f'] = np.array([1.3333333333, np.nan, 2.6666666666666666, 5.0])
arr['g'] = np.array([2.77777777777, 5.4, 3.4, np.nan])
# nothing for 'j'
現(xiàn)在嘗試打印 np.isnan 語句:
print(np.isnan(arr[1][3]))
True
添加回答
舉報
0/150
提交
取消