Home > other >  Reconcile with np.fromiter and multidimensional arrays in Python
Reconcile with np.fromiter and multidimensional arrays in Python

Time:09-13

I am working on coming up with a multi-dimensional array in order to come up with the following result in jupyter notebook.

I have tried several codes but I seem not to be able to produce the forth column with the number range of 30 - 35. The closest I have gone is using this code:

import numpy as np
from itertools import chain

def fun(i):
    return tuple(4*i   j for j in range(4))

a = np.fromiter(chain.from_iterable(fun(i) for i in range(6)), 'i', 6 * 4)
a.shape = 6, 4

print(repr(a))

I am expecting the following results:

array([[ 1,  2,  3, 30],
      [ 4,  5,  6, 31],
      [ 7,  8,  9, 32],
      [10, 11, 12, 33],
      [13, 14, 15, 34],
      [20, 21, 22, 35]])

CodePudding user response:

You can create a flat array with all your subsequent numbers like this:

import numpy as np
a = np.arange(1, 16)
print(a)
# output:
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]

Then you reshape it:

a = np.reshape(a, (5, 3))
print(a)
# output
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]
 [13 14 15]]

Then you add a new row:

a = np.vstack([a, np.arange(20, 23)])
print(a)
# output:
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]
 [13 14 15]
 [20 21 22]]

You create the column to add:

col = np.arange(30, 36).reshape(-1, 1)
print(col)
# output:
[[30]
 [31]
 [32]
 [33]
 [34]
 [35]]

You add it:

a = np.concatenate((a, col), axis=1)
print(a)
# output:
[[ 1  2  3 30]
 [ 4  5  6 31]
 [ 7  8  9 32]
 [10 11 12 33]
 [13 14 15 34]
 [20 21 22 35]]
  • Related