将一个float数组转为int数组
时间: 2024-02-09 19:09:14 浏览: 30
可以使用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`。
相关问题
将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`。
怎么把一个float型的numpy数组转为整型
你可以使用numpy的astype()函数将float型的numpy数组转为整型,例如:
```python
import numpy as np
float_array = np.array([1.2, 2.5, 3.7])
int_array = float_array.astype(int)
print(int_array)
```
输出结果为:
```python
[1 2 3]
```
相关推荐
![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)