numpy中 str 转float
时间: 2023-04-09 14:05:01 浏览: 730
可以使用 numpy 中的 astype() 方法将 str 转换为 float,例如:
```python
import numpy as np
str_num = '3.14'
float_num = np.array([str_num]).astype(np.float32)
print(float_num)
```
输出结果为:
```
[3.14]
```
相关问题
numpy中float转string
在NumPy中,可以使用numpy.array中的astype方法将浮点数转换为字符串,代码如下:
```
import numpy as np
arr = np.array([3.14, 2.718, 1.414], dtype=float)
str_arr = arr.astype(str)
print(str_arr)
# 输出:['3.14' '2.718' '1.414']
```
也可以使用numpy.array的round方法先将浮点数四舍五入,再使用astype方法转换为字符串。代码如下:
```
import numpy as np
arr = np.array([3.14159265, 2.71828183, 1.41421356], dtype=float)
rounded_arr = np.round(arr, 2)
str_arr = rounded_arr.astype(str)
print(str_arr)
# 输出:['3.14' '2.72' '1.41']
```
numpy.float64转成str
可以使用Python内置的str()函数将numpy.float64类型的数据转换为字符串类型。例如:
```python
import numpy as np
x = np.float64(3.1415926)
s = str(x)
print(s)
```
输出结果为:
```
3.1415926
```
另外,如果需要控制字符串的格式,可以使用Python内置的格式化字符串方法。例如:
```python
import numpy as np
x = np.float64(3.1415926)
s = f"{x:.2f}"
print(s)
```
输出结果为:
```
3.14
```
其中,":.2f"表示保留两位小数的浮点数格式。更多格式化字符串的用法可以参考Python官方文档。