我正在尝试使用从0到1的随机数的numpy数组:
import numpy as np
x = np.random.random((3,3))
产量
[[ 0.11874238 0.71885484 0.33656161]
[ 0.69432263 0.25234083 0.66118676]
[ 0.77542651 0.71230397 0.76212491]]
并且,从这个数组中,我需要值大于0.3的行,列组合。所以预期的输出应该如下:
(0,1),(0,2),(1,0),(1,2),(2,0),(2,1),(2,2)
能够提取item
(x [row] [column]的值),并尝试将输出写入文件。我尝试了以下命令:
with open('newfile.txt', 'w') as fd:
for row in x:
for item in row:
if item > 0.3:
print(item)
for row in item:
for col in item:
print(row,column,'\n')
fd.write(row,column,'\n')
然而,它引发了一个错误:
TypeError: 'numpy.float64' object is not iterable
此外,我搜索但无法找到如何从1而不是0开始numpy索引。例如,预期输出将如下所示:
(1,2),(1,3),(2,1),(2,3),(3,1),(3,2),(3,3)
你知道如何获得这些输出吗?
答案 0 :(得分:2)
在比较掩码上获得与该条件匹配的前两个轴的索引 here is my code:-
var rr = $('ddlAssignUser:selected').length;
alert(rr);
<select id="ddlAssignUser" class="form-control" runat="server" multiple="true"> </select>
,然后简单地用integer array indexing
索引 -
np.nonzero/np.where
如果您希望将这些索引列为元组列表,r,c = np.nonzero(x>0.3)
out = x[r,c]
这些索引 -
zip
要从zip(r,c)
开始,请添加1
,然后添加zip -
1
在zip(r+1,c+1)
上,您需要使用Python 3.x
:list()
和list(zip(r,c))
对其进行换行。
示例运行 -
list(zip(r+1,c+1))
将In [9]: x
Out[9]:
array([[ 0.11874238, 0.71885484, 0.33656161],
[ 0.69432263, 0.25234083, 0.66118676],
[ 0.77542651, 0.71230397, 0.76212491]])
In [10]: r,c = np.nonzero(x>0.3)
In [14]: zip(r,c)
Out[14]: [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)]
In [18]: zip(r+1,c+1)
Out[18]: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)]
In [13]: x[r,c]
Out[13]:
array([ 0.71885484, 0.33656161, 0.69432263, 0.66118676, 0.77542651,
0.71230397, 0.76212491])
写入文件 -
indices
使用np.savetxt
格式,如此 -
int
使用基于In [69]: np.savetxt("output.txt", np.argwhere(x>0.3), fmt="%d", comments='')
In [70]: !cat output.txt
0 1
0 2
1 0
1 2
2 0
2 1
2 2
的索引编制,将1
添加到1
输出 -
np.argwhere
答案 1 :(得分:1)
你可以使用np.where,它返回两个数组(当应用于2D数组时),行索引(和相应的列)满足你指定为参数的条件。 然后你可以压缩这两个数组来获取一个元组列表:
@IBAction func touchupInsideAction(_ sender: Any) {
firstLabel.alpha = 1.0
secondLabel.alpha = 1.0
}
@IBAction func touchDownAction(_ sender: Any) {
firstLabel.alpha = 0.5
secondLabel.alpha = 0.5
}
如果你想为每个元组的每个元素添加1(使用基于1的索引),要么循环遍历元组,要么为每个返回的数组加1:
list(zip(*np.where(x > 0.3)))