Home > Net >  Change Array starting at spefic index
Change Array starting at spefic index

Time:10-01

my lists look something like this:

A_List= [0,1,2,3,4,5,6,7,8] 
B_List=[0,10,20,30,40,50,60,70,80]
C_List=[0,100,200,300,400,500,600,700,800]
D_List = ... 

and so on.

Each value is type np.float64.

The values here are random, I only wanted to show that they are all the same length.

I now tried to write a loop that changes these lists starting at a specific index in that way, that all numbers including and above index 4 are subtracted by the value written in index 4.

i=4
while i <= len(A_List):
    
    A_List[i] = A_List[i] A_List[4]
    B_List[i] = B_List[i] B_List[4]
    C_List[i] = C_List[i] C_List[4]
    D_List[i] = D_List[i] D_List[4]
    ...

    i=i 1

Which just won't work. Error: can only concatenate str (not "numpy.float64") to str). I don't quite understand that, because I thought I'm substituting a float value with another float value. Thanks for the help in advance.

CodePudding user response:

Why don't you simply use numpy and not lists?

First create a 2D array:

A_List= [0,1,2,3,4,5,6,7,8] 
B_List=[0,10,20,30,40,50,60,70,80]
C_List=[0,100,200,300,400,500,600,700,800]

a = np.c_[A_List, B_List, C_List]
array([[  0,   0,   0],
       [  1,  10, 100],
       [  2,  20, 200],
       [  3,  30, 300],
       [  4,  40, 400],
       [  5,  50, 500],
       [  6,  60, 600],
       [  7,  70, 700],
       [  8,  80, 800]])

Then perform your subtraction:

>>> a-a[4]
array([[  -4,  -40, -400],
       [  -3,  -30, -300],
       [  -2,  -20, -200],
       [  -1,  -10, -100],
       [   0,    0,    0],
       [   1,   10,  100],
       [   2,   20,  200],
       [   3,   30,  300],
       [   4,   40,  400]])

If you want to apply your transform only on rows ≥ 4:

mask = np.tile((np.arange(len(a))>=4), (a.shape[1], 1)).T
np.where(mask, a-a[4], a)

output:

array([[  0,   0,   0],
       [  1,  10, 100],
       [  2,  20, 200],
       [  3,  30, 300],
       [  0,   0,   0],
       [  1,  10, 100],
       [  2,  20, 200],
       [  3,  30, 300],
       [  4,  40, 400]])
  • Related