I have a list of numpy arrays and want to firstly split the list and then concatenate all the arrays exiting in each sublist. Number of sublists is defined by:
JavaScript
x
2
1
n_sublist=2 # but in reality I have much more sublists
2
this is my list:
JavaScript
1
9
1
all_data=[np.array([[1., 2., 3.], [10., 11., 12.]]),
2
np.array([[5., 3., 1.]]),
3
np.array([[2., -1., 11.]]),
4
np.array([[4., -2., 31.], [1., 8., 8.]]),
5
np.array([[0., 0., 0.]]),
6
np.array([[22., 9., 7.]]),
7
np.array([[-4., 9., 21.], [5., 0., 0.]]),
8
np.array([[4., 1., 2.]])]
9
The length of all_data is 8 and it should be firstly modified to be a list of n_sublist
lists. I mean two sublists which first one has the first four arrays and second one has the last four arrays. Then, all the arrays of each sublist should be concatenated. Finally, I want the following list as output:
JavaScript
1
9
1
final_ls=[[[1., 2., 3.], [10., 11., 12.],
2
[5., 3., 1.],
3
[2., -1., 11.],
4
[4., -2., 31.], [1., 8., 8.]],
5
[[0., 0., 0.],
6
[22., 9., 7.],
7
[-4., 9., 21.], [5., 0., 0.],
8
[4., 1., 2.]]]
9
I tried the following method but I was not successful to do so:
JavaScript
1
6
1
A = all_data[:len(all_data)//n_sublist]
2
B = all_data[len(all_data)//n_sublist:]
3
A=[l.tolist() for l in A]
4
B=[l.tolist() for l in B]
5
final_ls=[A,B]
6
Advertisement
Answer
You can do:
JavaScript
1
4
1
n = len(all_data)//n_sublist
2
final_lst = [np.concatenate(all_data[:n]).tolist(),
3
np.concatenate(all_data[n:]).tolist() ]
4
Output:
JavaScript
1
12
12
1
[[[1.0, 2.0, 3.0],
2
[10.0, 11.0, 12.0],
3
[5.0, 3.0, 1.0],
4
[2.0, -1.0, 11.0],
5
[4.0, -2.0, 31.0],
6
[1.0, 8.0, 8.0]],
7
[[0.0, 0.0, 0.0],
8
[22.0, 9.0, 7.0],
9
[-4.0, 9.0, 21.0],
10
[5.0, 0.0, 0.0],
11
[4.0, 1.0, 2.0]]]
12
Note for general number n_sublist
:
JavaScript
1
3
1
final_lst = [np.concatenate(all_data[i*n:i*n+n]).tolist()
2
for i in range(n_sublist)]
3