numpy中 str 转float
时间: 2023-04-09 10:05:01 浏览: 894
可以使用 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']
```
unsupported operand type(s) for -: 'numpy.str_' and 'numpy.str_'
This error occurs when you try to perform a subtraction operation (-) between two numpy string objects. Numpy string objects are not numerical, and therefore cannot be subtracted from each other.
To fix this error, you need to make sure that the objects you are trying to subtract are numerical. You can convert numpy string objects to numerical data types using functions like int() or float().
For example, if you have two numpy string objects '10' and '5', you can convert them to integers and subtract them as follows:
```
a = '10'
b = '5'
result = int(a) - int(b)
print(result)
```
This will output: 5
Alternatively, you can also use the numpy function np.subtract() to perform element-wise subtraction between two numpy arrays.
```
import numpy as np
a = np.array(['10', '20', '30'])
b = np.array(['5', '10', '15'])
result = np.subtract(a.astype(int), b.astype(int))
print(result)
```
This will output: [ 5 10 15]
阅读全文