我有一个如下所示的numpy数组:
array([['18.0', '11.0', '5.0', ..., '19.0', '18.0', '20.0'],
['11.0', '14.0', '15.0', ..., '45.0', '26.0', '20.0'],
['1.0', '0.0', '1.0', ..., '3.0', '4.0', '17.0'],
...,
['nan', 'nan', 'nan', ..., 'nan', 'nan', 'nan'],
['nan', 'nan', 'nan', ..., 'nan', 'nan', 'nan'],
['nan', 'nan', 'nan', ..., 'nan', 'nan', 'nan']],
dtype='|S230')
但是将它转换为int数组会使np.nan值成为奇怪的值:
df[:,4:].astype('float').astype('int')
array([[ 18, 11, 5,
..., 19, 18,
20],
[ 11, 14, 15,
..., 45, 26,
20],
[ 1, 0, 1,
..., 3, 4,
17],
...,
[-9223372036854775808, -9223372036854775808, -9223372036854775808,
..., -9223372036854775808, -9223372036854775808,
-9223372036854775808],
[-9223372036854775808, -9223372036854775808, -9223372036854775808,
..., -9223372036854775808, -9223372036854775808,
-9223372036854775808],
[-9223372036854775808, -9223372036854775808, -9223372036854775808,
..., -9223372036854775808, -9223372036854775808,
-9223372036854775808]])
那么如何解决我的问题?
答案 0 :(得分:2)
据我所知,将浮点Nan
转换为整数类型是未定义的行为。号码:
-9223372036854775808
是最小的int64,即-2**63
。请注意,当我强制int32
时,我的系统会发生同样的事情:
>>> arr
array([['18.0', '11.0', '5.0', 'nan']],
dtype='<U4')
>>> arr.astype('float').astype(np.int32)
array([[ 18, 11, 5, -2147483648]], dtype=int32)
>>> -2**31
-2147483648
答案 1 :(得分:1)
这完全取决于您对结果的期望。 nan
属于float类型,因此将字符串'nan'
转换为float是没有问题的。但没有将其转换为int
值的定义。
我建议你以不同的方式处理它 - 首先选择你想要所有int
值的特定nan
(例如0),然后将整个数组转换为int
a = np.array(['1','2','3','nan','nan'])
a[a=='nan'] = 0 # this will convert all the nan values to 0, or choose another number
a = a.astype('int')
现在a
等于
array([1, 2, 3, 0, 0])