numpy.ndarra取最大值索引
时间: 2023-07-11 18:48:15 浏览: 63
可以使用numpy的argmax函数来取得ndarray中最大值的索引。例如,下面的代码可以取得数组a中最大值的索引:
```
import numpy as np
a = np.array([1, 3, 2, 4, 5])
max_index = np.argmax(a)
print(max_index) # 输出 4
```
如果想在多维数组中取得最大值的索引,可以指定axis参数来沿着指定的维度进行计算。例如,下面的代码可以取得数组b中每一行的最大值的索引:
```
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
max_indices = np.argmax(b, axis=1)
print(max_indices) # 输出 [2 2 2]
```
相关问题
unhashable type: 'numpy.ndarra
y'
这个错误通常是由于尝试将numpy数组作为字典的键而引起的。numpy数组是不可哈希的,因为它们是可变的。要解决这个问题,可以将numpy数组转换为元组或列表,然后将其用作字典的键。例如,如果有一个numpy数组a,可以使用tuple(a)或list(a)将其转换为元组或列表,然后将其用作字典的键。
TypeError: tofile() argument 2 must be str, not numpy.ndarra
这个错误是由于 `tofile()` 函数的第二个参数需要是字符串类型,而不是一个 NumPy 数组(`numpy.ndarray`)类型。要解决这个问题,你可以将数组转换为字符串,然后再传递给 `tofile()` 函数。你可以使用 `numpy.array2string()` 函数将数组转换为字符串,然后再传递给 `tofile()` 函数,例如:
```python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr_string = np.array2string(arr)
arr_string.tofile('file.txt')
```
这样,你就可以将数组以字符串的形式保存到文件中了。