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

Tal*_*ia 5 python numpy

我有一个tempsyntheticGroup26列的矩阵。我想将列的值(0,1,2,3,5)从更改floatint。这是我的代码:

tempsyntheticGroup2=tempsyntheticGroup2[:,[0,1,2,3,5]].astype(int)
Run Code Online (Sandbox Code Playgroud)

但它不能正常工作,我将其他列松开。

Jul*_*ien 5

我不认为你可以有一个 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]])
Run Code Online (Sandbox Code Playgroud)

否则,您可能需要将原始数组拆分为 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]])
Run Code Online (Sandbox Code Playgroud)

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