Home > Net >  Concise notation for NumPy array cration
Concise notation for NumPy array cration

Time:12-26

NumPy arrays are extremely convenient for expressing many common vector and array operations. The standard notation is:

import numpy as np

v = np.array([1, 2, 3, 4])
u = np.array([0.3, 0.4, 0.5])

I have many cases where I need a lot of different short np.array vectors and the boilerplate np.array(...) gets in a way of clarity. What are the practical solutions people use to reduce boilerplate in these cases? Is there any Python magic to help? Ideally, I would like to be able to write something along these lines:

v = <1, 2, 3, 4>
u = <0.3, 0.4, 0.5>

<> is just a random choice for illustration purpose.

CodePudding user response:

You can make a class and a corresponding instance with a single letter identifier defining its __getitem__ method to allow use of brackets in defining the numpy array shorthand:

import numpy as np

class Ä:
    def __getitem__(self,index):
        return np.array(index)
Ä = Ä()

usage:

V = Ä[1,2,3]

print(V,type(V)) # [1 2 3] <class 'numpy.ndarray'>

M = Ä[ [1,2,3],
       [4,5,6] ]

print(M)
[[1 2 3]
 [4 5 6]]

CodePudding user response:

You can use import like below:

from numpy import array as _

v = _([1, 2, 3, 4])
u = _([0.3, 0.4, 0.5])

Shorter:

import numpy as np

def _(*args)
    return np.array(args)

v = _(1, 2, 3, 4)
u = _(0.3, 0.4, 0.5)
  • Related