python中float数组转换为int数组
时间: 2024-05-08 11:15:39 浏览: 22
可以使用Python的内置函数`map()`来实现float数组转换为int数组,具体代码如下:
```python
float_arr = [1.2, 2.5, 3.7]
int_arr = list(map(int, float_arr))
print(int_arr)
```
输出结果:
```
[1, 2, 3]
```
其中,`map()`函数将`int()`函数应用到`float_arr`中的每个元素上,返回一个可迭代的map对象,最后使用`list()`函数将其转换为int数组。
相关问题
利用numpy将一个float32的数组转换为int32位的数组
可以使用numpy的astype()方法将float32数组转换为int32数组。astype()方法可以接受一个数据类型参数,用于指定转换后的类型。例如:
```python
import numpy as np
# 创建一个float32数组
float_arr = np.array([1.2, 3.5, 4.8], dtype=np.float32)
# 将float32数组转换为int32数组
int_arr = float_arr.astype(np.int32)
print(int_arr)
```
输出结果为:
```
[1 3 4]
```
在这个例子中,我们首先创建了一个包含三个浮点数的float32数组。然后使用astype()方法将该数组转换为int32数组。输出结果显示了转换后的int32数组。注意,浮点数被向下取整为最接近的整数。
将float数组转为int数组
可以使用Python中的列表推导式,将一个float类型的列表或数组转换为int类型的列表或数组。示例如下:
```python
float_list = [1.2, 2.3, 3.5, 4.9]
int_list = [int(x) for x in float_list]
print(int_list) # 输出 [1, 2, 3, 4]
```
在上面的代码中,通过列表推导式将`float_list`中的每个元素转换为int类型,得到了`int_list`。如果原来的数据是数组类型,可以使用`np.array()`函数将其转换为numpy数组,再利用numpy中的`astype()`方法将其转换为int类型。示例如下:
```python
import numpy as np
float_array = np.array([1.2, 2.3, 3.5, 4.9])
int_array = float_array.astype(int)
print(int_array) # 输出 [1 2 3 4]
```
在上面的代码中,`astype()`方法将`float_array`中的每个元素转换为int类型,得到了`int_array`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)