我有一个数组,并希望不提取特定范围内的所有条目
x = np.array([1,2,3,4])
condition = x<=4 and x>1
x_sel = np.extract(condition,x)
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我越来越
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)
如果我在没有并且仅检查一个条件的情况下也这样做
x = np.array([1,2,3,4])
condition = x<=4
x_sel = np.extract(condition,x)
Run Code Online (Sandbox Code Playgroud)
一切正常......对于courese,我可以在一个条件下应用该程序两次,但是在一行中没有解决方案吗?
提前谢谢了
你可以使用这个:
import numpy as np
x = np.array([1,2,3,4])
condition = (x <= 4) & (x > 1)
x_sel = np.extract(condition,x)
print(x_sel)
# [2 3 4]
Run Code Online (Sandbox Code Playgroud)
或者没有extract:
x_sel = x[(x > 1) & (x <= 4)]
Run Code Online (Sandbox Code Playgroud)