gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:21:11 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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

# 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 个不同的数组,一个包含保持 float 的列,另一个包含变为整数的列。

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]])

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

关于python - 将矩阵的某些列从 float 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com