我需要根据元素出现在其他replacement
数组
例如:
>>> main = np.random.randint(5, size=(3, 4))
>>> main
array([[1, 2, 4, 2],
[3, 2, 3, 2],
[4, 4, 2, 3]])
>>> repl = [2,3]
>>> main[main in repl] = -1
我想将repl
中的所有值更改为-1,因此我希望main为:
[[1, -1, 4, -1],
[-1, -1, -1, -1],
[4, 4, -1, -1]]
但是在尝试将ValueError
置于替换条件中时会引发in
ValueError:具有多个元素的数组的真值是不明确的。使用a.any()或a.all()
答案 0 :(得分:1)
我们可以使用np.in1d
创建所有此类事件的拼合蒙版,并在展平输入中将其设置为-1
,如此 -
main.ravel()[np.in1d(main, repl)] = -1
或者,我们可以使用np.putmask
,从而避免np.ravel()
避免显式展平,如此 -
np.putmask(main, np.in1d(main, repl), -1)
答案 1 :(得分:0)
你可以制作一个布尔掩码并像这样使用它:
/* Selects the first <th> child of the second <tr>
descendent of the <thead>, and also every first
<td> child contained within the <tbody>: */
thead tr:nth-child(2) th:first-child,
tbody td:first-child {
border-right-width: 0;
}
/* Selects the second <th> child of the second <tr>
descendent of the <thead>, and also every second
<td> child contained within the <tbody>: */
thead tr:nth-child(2) th:nth-child(2),
tbody td:nth-child(2) {
border-left-width: 0;
}
/* Selects every <th> element that follows the second
<th> child element of the second <tr> of the <thead>
using the general sibling ('~') combinator; and also
every <td> that appears after the second <td> of the
<tbody>: */
thead tr:nth-child(2) th:nth-child(2) ~ th,
tbody td:nth-child(2) ~ td {
border-left-width: 0;
}
/* Because we (presumably) want the final <th> and <td>
of each <tr> to retain its right-border, we here select
every <th> element which is not the last-child of its
parent which follows the second-child of the parent, and
similarly for the <td> elements: */
thead tr:nth-child(2) th:nth-child(2) ~ th:not(:last-child),
tbody td:nth-child(2) ~ td:not(:last-child) {
border-right-width: 0;
}
答案 2 :(得分:0)
不确定是否有任何本地numpy
方法,但在旧式方式python中你可以这样做:
import numpy as np
main = np.random.randint(5, size=(3, 4))
repl = [2,3]
for k1, v1 in enumerate(main):
for k2, v2 in enumerate(v1):
if(v2 in repl):
main[k1][k2] = -1
print(main)