作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 numpy 中执行一些相对简单的操作:
但是我最终得到了一个相当复杂的代码:
predictions = np.array([[1,-1,-1,-1],[-1,1,1,-1],[-1,-1,-1,1],[-1,-1,-1,-1]])
one_count = (predictions == 1).sum(1)
valid_rows_idx = np.where(one_count==1)
result = np.zeros(predictions.shape[0])
for idx in valid_rows_idx:
result[idx] = np.where(predictions[idx,:]==1)[1] + 1
如果我打印result
,程序会打印[ 1. 0. 4. 0.]
这是期望的结果。
我想知道是否有更简单的方法使用 numpy 编写最后一行。
最佳答案
我不确定这是否更好,但您可以尝试使用 argmax
为了那个原因。此外,您不需要使用 for 循环和 np.where
来获取有效索引:
predictions = np.array([[1,-1,-1,-1],[-1,1,1,-1],[-1,-1,-1,1],[-1,-1,-1,-1]])
idx = (predictions == 1).sum(1) == 1
result = np.zeros(predictions.shape[0])
result[idx] = (predictions[idx]==1).argmax(axis=1) + 1
In [55]: result
Out[55]: array([ 1., 0., 4., 0.])
或者您可以使用 np.where
和 argmax
在一行中完成所有这些工作:
predictions = np.array([[1,-1,-1,-1],[-1,1,1,-1],[-1,-1,-1,1],[-1,-1,-1,-1]])
In [72]: np.where((predictions==1).sum(1)==1, (predictions==1).argmax(axis=1)+1, 0)
Out[72]: array([1, 0, 4, 0])
关于python - 如何在numpy中找到给定行值的列索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35613034/
我是一名优秀的程序员,十分优秀!