Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling an array in python

I want to fill an array with some number, the output should be like this:

[[x1, y1, z1],
 [x1, y2, z2],
 [x2, y1, z3],
 [x2, y2, z4],
 [x3, y1, z5],
 [x3, y2, z6]]

I have the data x, y, and z (lists) with 3 values x, 2 values of y and 6 values of z inside the data.

I tried to create a new array and then fill it with for or while loop, but I can't get it fully filled.

How can I do it in numpy with python without filling it manually?

like image 718
Amri Rasyidi Avatar asked Sep 20 '25 06:09

Amri Rasyidi


2 Answers

Using np.repeat and np.tile on x and y respectively to get the desired columns and then stacking them together with z into one array:

import numpy as np

x = [1, 2, 3]
y = [4, 5]
z = [6, 7, 8, 9, 10, 11]

a = np.array([np.repeat(x, 2), np.tile(y, 3), z]).T

result:

array([[ 1,  4,  6],
       [ 1,  5,  7],
       [ 2,  4,  8],
       [ 2,  5,  9],
       [ 3,  4, 10],
       [ 3,  5, 11]])
like image 86
Andreas K. Avatar answered Sep 21 '25 19:09

Andreas K.


For a pure Python solution, to work with any list size.

x = [11,12,13,14,15]
y = [21,23,24]
z = [31,32,33,34,35,36,37]

This verbose code:

tmp = []
for i in range(max(len(x), len(y), len(z))):
    for yy in y:
        tmp.append([x[i%len(x)], yy])

for i in range(len(tmp)):
    tmp[i].append((z[i%len(z)]))

Returns

# [[11, 21, 31],
#  [11, 23, 32],
#  [11, 24, 33],
#  [12, 21, 34],
#  [12, 23, 35],
#  [12, 24, 36],
#  [13, 21, 37],
#  [13, 23, 31],
#  [13, 24, 32],
#  [14, 21, 33],
#  [14, 23, 34],
#  [14, 24, 35],
#  [15, 21, 36],
#  [15, 23, 37],
#  [15, 24, 31],
#  [11, 21, 32],
#  [11, 23, 33],
#  [11, 24, 34],
#  [12, 21, 35],
#  [12, 23, 36],
#  [12, 24, 37]]
like image 44
iGian Avatar answered Sep 21 '25 20:09

iGian