Home > Net >  Appending list of arrays in Python
Appending list of arrays in Python

Time:12-12

I have a list A containing multiple arrays of different shape. I want to append these arrays into a single array with multiple lists. But there is an error. I also show the expected output.

import numpy as np
arB=[]

A=[np.array([[ 42,  63],
[ 84,  95],
[118, 129],
[129, 140],
[140, 151],
[185, 196],
[196, 207],
[208, 219]]),np.array([[ 21,  42],
[ 63,  84],
[ 95, 106],
[106, 117],
[117, 118],
[207, 208]])]

for i in range(0,len(A)):
    for j in range(0,len(A[i])):
        for k in range(0,2):
            B=A[i,j,k]
            arB.append(B)
            B=np.array(arB)
print([B])

The error is

in <module>
    B=A[i,j,k]

TypeError: list indices must be integers or slices, not tuple

The expected output is

array([[42,  63, 84,  95, 118, 129, 129, 140, 140, 151, 185, 196, 196, 207, 208, 219],
[[ 21,  42, 63,  84, 95, 106,106, 117, 117, 118, 207, 208]])

CodePudding user response:

A is a list

[array([[ 42,  63],
       [ 84,  95],
       [118, 129],
       [129, 140],
       [140, 151],
       [185, 196],
       [196, 207],
       [208, 219]]), array([[ 21,  42],
       [ 63,  84],
       [ 95, 106],
       [106, 117],
       [117, 118],
       [207, 208]])]

You cannot assign three values simultaneously in index

A[i,j,k]

This is why you are getting error:

TypeError: list indices must be integers or slices, not tuple

CodePudding user response:

Code:-

import numpy as np
arB=[]
A=[np.array([[ 42,  63],
[ 84,  95],
[118, 129],
[129, 140],
[140, 151],
[185, 196],
[196, 207],
[208, 219]]),np.array([[ 21,  42],
[ 63,  84],
[ 95, 106],
[106, 117],
[117, 118],
[207, 208]])]
for i in range(0,len(A)):
    temp=[]
    for j in range(0,len(A[i])):
        for k in range(0,2):
            B=A[i][j][k]
            temp.append(B)
    arB.append(temp)
print(type(arB))
print(arB)

This will give output:-

<class 'list'>
[[42, 63, 84, 95, 118, 129, 129, 140, 140, 151, 185, 196, 196, 207, 208, 219], [21, 42, 63, 84, 95, 106, 106, 117, 117, 118, 207, 208]]
Convert this list form into an array..!

CodePudding user response:

You can use list comprehension:

B = [a.reshape(-1).tolist() for a in A]

If you really need an array of lists, you have to create it specfying dtype=object, since each list has different size:

B = np.array([a.reshape(-1).tolist() for a in A], dtype=object)

CodePudding user response:

Simply apply hstack (or equivalent np.concatenate) to each of the arrays in the list:

In [397]: A1 = [np.hstack(i) for i in A]

In [398]: A1
Out[398]: 
[array([ 42,  63,  84,  95, 118, 129, 129, 140, 140, 151, 185, 196, 196,
        207, 208, 219]),
 array([ 21,  42,  63,  84,  95, 106, 106, 117, 117, 118, 207, 208])]

You could add np.array(A1, dtype=object), but why bother. You started with a list, why not stick with it.

  • Related