Issue
How can I write a code that changes the values of each individual arrays within the multidimensional array a
to zeroes right after there was a negative or zero value for the a
index or a value that is -100 or less for the b
index. So the second array within a
has no negative values but b
has a -100 at the fourth index so everything after the fourth index is gonna be zeroes. [45,50,60,30,23.2,232,-44,12,23]
30
and the values right after it would turn into zeroes resulting in the output: [45,50,60,0,0,0,0,0,0]
. The Expected Output with the dtype ="object"
would have worked if not all the rows would have had the same length. How would I be able to get my Expected Output?
import numpy as np
a = np.array([[12,45,50,-600,30,23.2,232,-44,12],
[45,50,60,30,23.2,232,-44,12,23],
[50,60,30,23.2,232,-44,12,34,12],
[60,30,23.2,232,-44,12,120,3,4],
[-300,23.2,232,-44,12,23,23,2,12],
[23.2,-232,-44,12,34,1,2,300.3,5]], dtype='object')
b= np.array([-12.4,-13.4,-44,-100,-6.3,-11,-10,-1.1,-0.3])
#Going through rows
for row,l in enumerate(a):
#inside row iteration
for counter,i in enumerate(l):
if i<0 or b[counter]<=-100:
l[l.index(i):] = [0] * len(l[l.index(i):])
Output:
AttributeError: 'numpy.ndarray' object has no attribute 'index'
Expected Output:
[[12,45,50,0,0,0,0,0,0],
[45,50,60,0,0,0,0,0,0],
[50,60,30,0,0,0,0,0,0],
[60,30,23.2,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[23.2,0,0,0,0,0,0,0,0]]
Solution
You should try:
for row,l in enumerate(a):
#inside row iteration
l = l.tolist()
for counter,i in enumerate(l):
if i<0 or b[counter]<=-100:
a[row, l.index(i):] = [0] * len(l[l.index(i):])
print(a)
Output:
[[12 45 50 0 0 0 0 0 0]
[45 50 60 0 0 0 0 0 0]
[50 60 30 0 0 0 0 0 0]
[60 30 23.2 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0]
[23.2 0 0 0 0 0 0 0 0]]
The reason it didn't work for you is because you need to convert it into a list before indexing it, also you got to assign it back into the array a
Answered By - U12-Forward
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.