nonzero = x != 0 # we only care about places where x isn't 0
# Get tan, then divide by x, but only where x is not 0
nonzero_tan = np.tan(x, where=nonzero)
nonzero_tanc = np.divide(nonzero_tan, x, where=nonzero)
# Where x is not zero, use tan(x)/x, and use 1 everywhere else
tanc = np.where(nonzero, nonzero_tanc, 1)
使用掩码对每个元素的条件进行编码:
可以对满足条件的数据部分应用numpy操作:
全部(减少冗余操作):
后脚本
根据我的选择,@jirasaimok's excellent answer是一种更优雅的(numpythonic,如果您愿意的话)方法来完成同样的事情:避免每个元素进行一次以上的计算,并避免零除法。我建议可以使用
tan
和divide
的out
关键字进一步增强他们的答案,以避免分配和复制不必要的临时数组:或者更好:
你可以简单地做:
可以使用^{} ,并将} 和^{} 。你知道吗
where
参数设置为^{np.where(cond, a, b)
给出一个数组,其中来自a
的值用于cond
的真实元素,b
的元素用于cond
的虚假元素。你知道吗np.divide
和np.tan
的where
参数告诉它们只在另一个数组中为真的位置执行操作,并保留一些未初始化的其他元素(因此它们可以是任何元素,但这并不重要,因为这里不使用它们)。你知道吗正如hpaulj在他们的注释中所建议的,您还可以通过使用
np.divide
的out
参数来定义输出数组的默认值来组合最后两个步骤:相关问题 更多 >
编程相关推荐