When I execute this python code, I got an error message : ValueError: setting an array element with a sequence.
What's the problem? could you help me?
a=np.array([1,3,5,7,9], dtype=int)
c=np.array([3,4,7,8,9], dtype=int)
b=np.zeros(len(a))
for i in range(len(a)):
b[i]= np.where(a == int(c[i]))
CodePudding user response:
The problem lies in b[i]= np.where(a == int(c[i]))this returns an array that only contains a single element in your example. However, v is also one dimensional and you have to assign scalars not arrays. If you are sure that the search only return 1 element, you can do b[i]= np.where(a == int(c[i]))[0]
CodePudding user response:
You can maybe try to append it to b instead of replacing the value?
B.append(np.where( a == c[i]))
Also try using if conditions inside the for loop :)
CodePudding user response:
The problem lies with your array b. Since it is an array, it is not as flexible as a list. Since your np.where statement sometimes returns an empty array or even possibly an array with more scalars in it, it is a bit problematic.
You will be better of to define b as a list:
a=np.array([1,3,5,7,9], dtype=int)
c=np.array([3,4,7,8,9], dtype=int)
b=[]
for i in range(len(a)):
b.append(np.where(a==c[i])[0])
print(b)
[array([1]),
array([], dtype=int64),
array([3]),
array([], dtype=int64),
array([4])]
Only if you are entirely certain that your np.where statement will return one and only one scalar, you can use the solution of @Simon Hawe.
Do note that this returns the indexes of a where the statement is True! If you want the value itself, the code becomes
a=np.array([1,3,5,7,9], dtype=int)
c=np.array([3,4,7,8,9], dtype=int)
b=[]
for i in range(len(a)):
b.append(a[np.where(a==c[i])])
print(b)
[array([3]),
array([], dtype=int64),
array([7]),
array([], dtype=int64),
array([9])]
