-1

I am having trouble iterating through a list and applying an algorithm which changes certain values in that list to new ones. This is my current code. I keep getting errors in multiple ways ive tried to replace the values.

array=[0,1,2,34,44,55,343,22,11,66,44,33]
for x in array:
    if x==0:
        y='Nan'
        array.replace(x,y)
    if x==1:
        y=0
        array.replace(x,y)
    if x==2:
        y=1
        array.replace(x,y)
    if x >= 3 and x < 23:
        y=(x-2)*50
        array.replace(x,y)
    if x >=23 and x <63:
        y=(x-12)*100
        array.replace(x,y)
    if x == 63:
        y=5500
        array.replace(x,y)
    if x >= 64 and x <= 67:
        y=(x-58)*1000
        array.replace(x,y)
    if x >= 68:
        y = 10000 
        array.replace(x,y)
print(array)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • I'm getting `AttributeError: module 'pandas' has no attribute 'arr'`. What were you expecting `pd.arr` to do? Please provide a [mre]. – wjandrea Oct 11 '20 at 17:59
  • @wjandrea removed that portion. I just need to replace values in my array with new values from my if statements – Swagdaddymuffin Oct 11 '20 at 18:19
  • OK, now I'm getting `AttributeError: 'list' object has no attribute 'replace'`. See [finding and replacing elements in a list](https://stackoverflow.com/q/2582138/4518341) for working solutions. – wjandrea Oct 11 '20 at 18:28

1 Answers1

1

You can replace a given element in the list by doing the following:

list[index] = new_value

So,

array[array.index(x)] = y # array.index(x) will give you the position of x in array

In sum, I would do:

array=[0,1,2,34,44,55,343,22,11,66,44,33]

for i, x in enumerate(array): # use the direct i value instead of array.index(x)
    y = None
    if x == 0:
        y = 'NaN'
    elif x == 1:
        y = 0
    elif x == 2:
        y = 1
    elif x >= 3 and x < 23:
        y = (x-2)*50
    elif x >=23 and x <63:
        y = (x-12)*100
    elif x == 63:
        y = 5500
    elif x >= 64 and x <= 67:
        y = (x-58)*1000
    elif x >= 68:
        y = 10000 

    if y is not None:
        array[i] = y

print(array)