python – 将矩阵的某些列从float转换为int

我有一个矩阵tempsyntheticGroup2有6列.我想将列(0,1,2,3,5)的值从float更改为int.这是我的代码:

tempsyntheticGroup2=tempsyntheticGroup2[:,[0,1,2,3,5]].astype(int)

但它没有正常工作,我松开了其他列.

最佳答案 我不认为你可以有一个numpy数组,其中一些元素是整数,一些是浮点数(每个数组只有一个可能的dtype).但是如果你只想舍入到较低的整数(同时将所有元素保持为浮点数),你可以这样做:

# define dummy example matrix
t = np.random.rand(3,4) + np.arange(12).reshape((3,4))

array([[  0.68266426,   1.4115732 ,   2.3014562 ,   3.5173022 ],
       [  4.52399807,   5.35321628,   6.95888015,   7.17438118],
       [  8.97272076,   9.51710983,  10.94962065,  11.00586511]])



# round some columns to lower int
t[:,[0,2]] = np.floor(t[:,[0,2]])
# or
t[:,[0,2]] = t[:,[0,2]].astype(int)

array([[  0.        ,   1.4115732 ,   2.        ,   3.5173022 ],
       [  4.        ,   5.35321628,   6.        ,   7.17438118],
       [  8.        ,   9.51710983,  10.        ,  11.00586511]])

否则你可能需要将原始数组拆分为2个不同的数组,其中一个包含保留浮点数的列,另一个包含成为整数的列.

t_int =  t[:,[0,2]].astype(int)

array([[ 0,  2],
       [ 4,  6],
       [ 8, 10]])


t_float = t[:,[1,3]]

array([[  1.4115732 ,   3.5173022 ],
       [  5.35321628,   7.17438118],
       [  9.51710983,  11.00586511]])

请注意,您必须相应地更改索引以访问您的元素…

点赞