[英]Converting some columns of a matrix from float to 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]])
請注意,您必須相應地更改索引以訪問您的元素...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.