Who can explain how to loop add an element to the numpy array by condition?
I wrote some code that should do add element 2
if i element of array A
is 0
and add element 1
if i element of array A
is not 0
.
Here is the code itself:
import numpy as np
def finalconcat(somearray):
for i in somearray:
arraysome=[]
if somearray[i]==0:
arraysome=np.append(arraysome,[2],axis=0)
else:
arraysome=np.append(arraysome,[1],axis=0)
return arraysome
Let me give you an example:
A=np.array([1,0,2,3,4,5])
C=finalconcat(B)
print(C)
It should come out:
[1,2,1,1,1,1]
But it comes out like:
[1.]
Please explain to me what is wrong here, I just don't understand what could be wrong...
CodePudding user response:
You have several issues:
arraysome=[]
is inside your loop so for each iteration ofsomearray
you are emptyingarraysome
. Consequently, you can never end up with more than one element inarraysome
when you are all done.- You have
for i in somearray
. On each iterationi
will be the next element ofsomearray
; it will not be iterating indices of the array. Yet later you haveif somearray[i]==0:
. This should just beif i==0:
. - If you want the resulting elements of
arraysome
to be integers rather than floats, then you should initialize it to be a annumpy
array of integers. - You have
C=finalconcat(B)
, butB
is not defined. - You should really spend some time reading the PEP 8 – Style Guide for Python Code.
import numpy as np
def finalconcat(somearray):
arraysome = np.array([], dtype=np.int)
for i in somearray:
if i == 0:
arraysome = np.append(arraysome, [2], axis=0)
else:
arraysome = np.append(arraysome, [1], axis=0)
return arraysome
a = np.array([1, 0, 2, 3, 4, 5])
c = finalconcat(a)
print(c)
Prints:
[1 2 1 1 1 1]