Link_tester
Link_tester

Reputation: 1081

how to modify a column of numpy arrays stored in a list

I have a list of numpy arrays and want to modify some numbers of arrays. This is my simplified list:

first_list=[np.array([[1.,2.,0.], [2.,1.,0.], [6.,8.,3.], [8.,9.,7.]]),
            np.array([[1.,0.,2.], [0.,0.,2.], [5.,5.,1.], [0.,6.,2.]])]

I have a factor which defines how many splits I have in each arrays:

spl_array=2.

it means each array of the list can be splited into 2 ones. I want to add a fixed value (3.) into last column of each split of each array and also copy the last split and subtract this value (3.) from the third column of this copied split. Finally I want to have it as following:

final_list=[np.array([[1.,2.,3.], [2.,1.,3.], [6.,8.,6.], [8.,9.,10.], \
                      [6.,8.,0.], [8.,9.,4.]]), # copied and subtracted
            np.array([[1.,0.,5.], [0.,0.,5.], [5.,5.,4.], [0.,6.,5.], \
                      [5.,5.,-2.], [0.,6.,-1.]])] # copied and subtracted

I tried some for loops but I totaly lost. In advance , I do appreciate any help.

final_list=[]
for i in first_list:
    each_lay=np.split (i, spl_array)
    for j in range (len(each_lay)):
        final_list.append([each_lay[j][:,0], each_lay[j][:,1], each_lay[j][:,2]+3])

Upvotes: 0

Views: 54

Answers (1)

Corralien
Corralien

Reputation: 120409

Is it what you expect:

m = np.asarray(first_list)
m = np.concatenate((m, m[:, 2:]), axis=1)

m[:, :4, 2] += 3
m[:, 4:, 2] -= 3

final_list = m.tolist()
>>> m
array([[[  1.,   2.,   3.],
        [  2.,   1.,   3.],
        [  6.,   8.,   6.],
        [  8.,   9.,  10.],
        [  6.,   8.,   0.],
        [  8.,   9.,   4.]],
       [[  1.,   0.,   5.],
        [  0.,   0.,   5.],
        [  5.,   5.,   4.],
        [  0.,   6.,   5.],
        [  5.,   5.,  -2.],
        [  0.,   6.,  -1.]]])

Upvotes: 1

Related Questions