(Python) 如何使用 [:] 语法对数组的每个元素使用条件语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45848612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
(Python) How to use conditional statements on every element of array using [:] syntax?
提问by Juanig
If i need to ask a condition on every element of a numpy.ndarray of integers, do I have to use a for loop
如果我需要在整数 numpy.ndarray 的每个元素上询问条件,我是否必须使用 for 循环
for i in range(n):
if a[i] == 0:
a[i] = 1
or can I ask the question using [:] syntax
或者我可以使用 [:] 语法提问吗
if a[:] == 0:
#...
I know the previous is wrong, but is there any way of doing something similar?
我知道以前是错误的,但是有什么办法可以做类似的事情吗?
回答by Christian Dean
You can use the all
builtin function to accomplish what your asking:
您可以使用all
内置函数来完成您的要求:
all(i == 0 for i in a)
Example:
例子:
>>> a = [1, 0, 0, 2, 3, 0]
>>> all(i == 0 for i in a)
False
Note however that behinds the scenes, all
still uses a for loop. It's just implemented in C:
但是请注意,在幕后,all
仍然使用 for 循环。它只是在 C 中实现的:
for (;;) {
item = iternext(it);
if (item == NULL)
break;
cmp = PyObject_IsTrue(item);
Py_DECREF(item);
if (cmp < 0) {
Py_DECREF(it);
return NULL;
}
if (cmp == 0) {
Py_DECREF(it);
Py_RETURN_FALSE;
}
EDIT: Given your most recent edits, what you probably want instead is to use a list comprehension with the ternary operator:
编辑:鉴于您最近的编辑,您可能想要的是使用带有三元运算符的列表理解:
[1 if i == 0 else i for i in a]
Example:
例子:
>>> a = [1, 0, 0, 2, 3, 0]
>>> [1 if i == 0 else i for i in a]
[1, 1, 1, 2, 3, 1]
回答by FabienP
For testing a condition on every element of a numpy.ndarray at once, as the title could suggest:
对于numpy.ndarray的每一个元素上进行测试的条件一次,因为标题可能表明:
use numpy's np.all
for that:
使用numpy的np.all
:
if np.all(a == 0):
# ...
Despite it is not lazy, np.all
is vectorized and very fast
尽管它并不懒惰,但np.all
已矢量化且速度非常快
# arrays of zeros
>>> a = np.zeros((1000000))
>>> %timeit np.all(a == 0) # vectorized, very fast
10000 loops, best of 3: 34.5 μs per loop
>>>%timeit all(i == 0 for i in a) # not vectorized...
100 loops, best of 3: 19.3 ms per loop
# arrays of non-zeros
>>> b = np.ones((1000000))
>>> %timeit np.all(b == 0) # not lazy, iterates through all array
1000 loops, best of 3: 498 μs per loop
>>> %timeit all(i == 0 for i in b) # lazy, return false at first 1
1000000 loops, best of 3: 561 ns per loop
# n-D arrays of zeros
>>> c = a.reshape((100, 1000)) # 2D array
>>> %timeit np.all(c == 0)
10000 loops, best of 3: 34.7 μs per loop # works on n-dim arrays
>>> %timeit all(i == 0 for i in c) # wors for a 1D arrays only
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
For testing a condition on every element of a numpy.ndarray iteratively:
为了迭代地测试 numpy.ndarray 的每个元素的条件:
for i in range(n):
if a[i] == 0:
a[i] = 1
can be replaced by np.where
可以替换为 np.where
a = np.where(a == 0, 1, a) # set value '1' where condition is met
EDIT: precisions according to the OP's comments
编辑:根据OP的评论精度
回答by Cody Piersall
Assuming a
is your array, and you want to change values of a
that are greater than 1 to be equal to 1:
假设a
是您的数组,并且您希望将a
大于 1 的值更改为等于 1:
a[a > 1] = 1
This works because the expression a > 1
creates a mask array, and when a mask array is used as an index (which it is here), the operation only applies on the True
indices.
这是有效的,因为表达式a > 1
创建了一个掩码数组,并且当一个掩码数组用作索引(它在这里)时,该操作仅适用于True
索引。
回答by Sergey Belash
if you need not just check, but map all 0 --> 1, use map
:
如果您不仅需要检查,还需要映射所有 0 --> 1,请使用map
:
map(lambda x: 1 if x==0 else x, a)