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:
n_sublist=2 # but in reality I have much more sublists
this is my list:
all_data=[np.array([[1., 2., 3.], [10., 11., 12.]]), np.array([[5., 3., 1.]]), np.array([[2., -1., 11.]]), np.array([[4., -2., 31.], [1., 8., 8.]]), np.array([[0., 0., 0.]]), np.array([[22., 9., 7.]]), np.array([[-4., 9., 21.], [5., 0., 0.]]), np.array([[4., 1., 2.]])]
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:
final_ls=[[[1., 2., 3.], [10., 11., 12.], [5., 3., 1.], [2., -1., 11.], [4., -2., 31.], [1., 8., 8.]], [[0., 0., 0.], [22., 9., 7.], [-4., 9., 21.], [5., 0., 0.], [4., 1., 2.]]]
I tried the following method but I was not successful to do so:
A = all_data[:len(all_data)//n_sublist] B = all_data[len(all_data)//n_sublist:] A=[l.tolist() for l in A] B=[l.tolist() for l in B] final_ls=[A,B]
Advertisement
Answer
You can do:
n = len(all_data)//n_sublist final_lst = [np.concatenate(all_data[:n]).tolist(), np.concatenate(all_data[n:]).tolist() ]
Output:
[[[1.0, 2.0, 3.0], [10.0, 11.0, 12.0], [5.0, 3.0, 1.0], [2.0, -1.0, 11.0], [4.0, -2.0, 31.0], [1.0, 8.0, 8.0]], [[0.0, 0.0, 0.0], [22.0, 9.0, 7.0], [-4.0, 9.0, 21.0], [5.0, 0.0, 0.0], [4.0, 1.0, 2.0]]]
Note for general number n_sublist
:
final_lst = [np.concatenate(all_data[i*n:i*n+n]).tolist() for i in range(n_sublist)]