I have a 2D array of shape say 5000x10, basically like 10 types of values taken 5000 times (thus 5000 profiles), and I want to find see how many of these profiles altogether have a value greater than a number like X. For eg,
a=np.array([[1,2,3,4,5],[1,2,3,4,6],[-1,2,3,4,-5]])
Here a has a shape of 3x5, so 3 profiles of 6 types. I want to see how many profiles are completely positive (>0) or fully greater than X, so I have used the following code:
d=0
for x in range(3):
if(a[x,:].all()>0):
d=d+1
But d returns 3, which should not be the case, as a[2,:]
is not completely positive. What can I do in this case?
Well, you try to use list's .all()
method, which does not exist, so your code shouldn't work at all:
>>> a = [1, 2, 3]
>>> a.all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'all'
And if it were a NumPy array, as per @AKX's comment , its .all(…)
method would just test if all elements evaluate to True
, but negative integers also evaluate to True
in Python:
>>> bool(-1)
True
What you should do is use built-in all(…)
function :
a = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 6], [-1, 2, 3, 4, -5]]
d = 0
for inner_list in a:
if all(x > 0 for x in inner_list):
d += 1
Or you could use sum(…)
function :
d = sum(1 for inner_list in a if all(x > 0 for x in inner_list))
As you can see, I've used for inner_list in a
in both cases, which is just a nicer way to iterate over list's elements than using its indexes — in your case it would actually be equivalent to:
for i in range(len(a)): # or "in range(3)" in your specific case
inner_list = a[x]
...
a = [[1,2,3,4,5],[1,2,3,4,6],[-1,2,3,4,-5]]
d = 0
for x in range(3):
if (all(e > 0 for e in a[x])):
d = d+1
For a[x]
equal to [-1,2,3,4,-5]
, [e > 0 for e in a[x]]
is equal to [False, True, True, True, False]
. Then, all(e > 0 for e in a[x])
checks if all values in [False, True, True, True, False]
are True
.
below is the code which might help
a=np.array([[1,2,3,4,5],[1,2,3,4,6],[-1,2,3,4,-5]])
d=0
for iter1 in range (a.shape[0]):
flag = True
for iter2 in range (a.shape[1]):
print (a[iter1][iter2])
if a[iter1][iter2] < 0:
flag = False
print("moving to next row check the flag value="+ str(flag))
if flag:
d = d+1
print("Number of profiles which are positive="+ str(d))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.