的Python:在数组元素条件 [英] Python: Conditional elements in array
问题描述
这是一个完整的Python新手问题。
A question from a complete Python novice.
我有一个列数组,我需要根据应用到另一个阵列条件语句来迫使某些值为零。我已经发现两种解决方案,这两者都提供了正确的答案。但它们消耗了较大的阵列我通常需要(> 1E6元素)都相当的时间 - 我也怀疑这是编程技术较差。这两个版本是:
I have a column array where I need to force certain values to zero depending on a conditional statement applied to another array. I have found two solutions, which both provide the correct answer. But they are both quite time consuming for the larger arrays I typically need (>1E6 elements) - also I suspect that it is poor programming technique. The two versions are:
from numpy import zeros,abs,multiply,array,reshape
def testA(y, f, FC1, FC2):
c = zeros((len(f),1))
for n in xrange(len(f)):
if abs(f[n,0]) >= FC1 and abs(f[n,0]) <= FC2:
c[n,0] = 1.
w = multiply(c,y)
return w
def testB(y, f, FC1, FC2):
z = [(abs(f[n,0])>=FC1 and abs(f[n,0])<=FC2) for n in xrange(len(f))]
z = multiply(array(z,dtype=float).reshape(len(f),1), y)
return z
输入数组的数组列,因为这匹配的后处理工作要做。测试可以像来完成:
The input arrays are column arrays as this matches the post processing to be done. The test can be done like:
>>> from numpy.random import normal as randn
>>> fs, N = 1.E3, 2**22
>>> f = fs/N*arange(N).reshape((N,1))
>>> x = randn(size=(N,1))
>>> w1 = testA(x,f,200.,550.)
>>> z1 = testB(x,f,200.,550.)
在我的笔记本电脑的种皮需要18.7秒和 TESTB 需要19.3 - 既为N = 2 ** 22。在 TESTB 我也试过,包括Z = [无] * LEN(六),以preallocate在另一个线程建议,但并不真正使任何区别。
On my laptop testA takes 18.7 seconds and testB takes 19.3 - both for N=2**22. In testB I also tried to include "z = [None]*len(f)" to preallocate as suggested in another thread but this doesn't really make any difference.
我有两个问题,我希望能有相同的答案:
I have two questions, which I hope to have the same answer:
- 什么是正确的Python解决这个问题?
- 有什么我能做得到的答案快?
我特意不使用任何时候都使用Python的编译 - 例如我想先有一定的工作code。也希望一些东西,这是很好的Python的风格。我希望能够得到执行时间为N = 2 ** 22两秒钟所以下面。所以执行时间事执行此特定的操作将被使用很多次。
I have deliberately not used any time at all using compiled Python for example - I wanted to have some working code first. Hopefully also something, which is good Python style. I hope to be able to get the execution time for N=2**22 below two seconds or so. This particular operation will be used many times so the execution time does matter.
我提前道歉,如果问题是愚蠢的 - 我一直没能找到一个答案并不总是方便Python文档的压倒性数量或在另一个线程
I apologize in advance if the question is stupid - I haven't been able to find an answer in the overwhelming amount of not always easily accessible Python documentation or in another thread.
推荐答案
使用布尔数组访问量阵列Y元素:
use bool array to access elements in array y:
def testC(y, f, FC1, FC2):
f2 = abs(f)
idx = (f2>=FC1) & (f2<=FC2)
y[~idx] = 0
return y
这篇关于的Python:在数组元素条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!