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

时间:2015-10-29 02:21:07

标签: python numpy

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

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

但它无法正常工作,我松开了其他列。

2 个答案:

答案 0 :(得分:3)

我不认为你可以拥有一个numpy数组,其中包含一些int元素,还有一些是float(每个数组只有一个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]])

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

答案 1 :(得分:0)

我认为您使用错误的语法来获取列数据。

阅读这篇文章。

How do you extract a column from a multi-dimensional array?

相关问题