Home > OS >  Store user-defined object in numpy array in Python
Store user-defined object in numpy array in Python

Time:01-18

How can I store an object of user-defined class in numpy array ?

I have a class like this:

class Node():
   
    def __init__(self):
        
        self.g = 0

import numpy as np

def main():
        node1 = Node()
        node2 = Node()

        my_array = np.empty( shape=(2, 3), dtype = 'Node' )
        my_array[0][1] = node1
        my_array[1][1] = node2

        print(my_array)

The above code throws the error: TypeError: data type "Node" not understood.

CodePudding user response:

Solution 1:

class Node():
   
    def __init__(self):
        
        self.g = 0

import numpy as np

def main():
        node1 = Node()
        node2 = Node()

        my_array = np.empty( shape=(2, 3), dtype = object)
        my_array[0][1] = node1
        my_array[1][1] = node2

        print(my_array)

Solution 2:

class Node1():
   
    def __init__(self,data):
        
        self.g = 0
        self.data= 1

import numpy as np

def main():
        node1 = Node1(1)
        node2 = Node1(2)

        my_array = np.empty( shape=(2, 3), dtype = np.dtype(Node1))
        my_array[0][1] = node1
        my_array[1][1] = node2

        print(my_array)

Please go through document: https://numpy.org/doc/stable/reference/arrays.dtypes.html

CodePudding user response:

Your class with a minor enhancement:

In [198]: class Node():
     ...:     def __init__(self,i):
     ...:         self.g = i
     ...:     def __repr__(self):
     ...:         return "<Node %s %s>"%(self.g, id(self))
     ...: 
     ...: node1 = Node(1)
     ...: node2 = Node(2)
     ...: 

The instances:

In [199]: node1
Out[199]: <Node 1 140575230534224>
In [200]: node2
Out[200]: <Node 2 140575230535904>

a list containing the instances:

In [201]: alist = [node1, node2]
In [202]: alist
Out[202]: [<Node 1 140575230534224>, <Node 2 140575230535904>]

An object dtype array:

In [203]: arr = np.empty(3, dtype=object)
In [204]: arr
Out[204]: array([None, None, None], dtype=object)

Like a list it can "hold" an instance, a number, or a list of nodes:

In [205]: arr[0]=node1
In [206]: arr[1]=123
In [207]: arr[2]=[node2, node1]
In [208]: arr
Out[208]: 
array([<Node 1 140575230534224>, 123,
       list([<Node 2 140575230535904>, <Node 1 140575230534224>])],
      dtype=object)

Use list comprehension to fetch the attribute:

In [209]: [a.g for a in alist]
Out[209]: [1, 2]

or conditional fetch - from the list or array:

In [211]: [a.g for a in alist if isinstance(a,Node)]
Out[211]: [1, 2]
In [212]: [a.g for a in arr if isinstance(a,Node)]
Out[212]: [1]

the array itself can't fetch instance attributes:

In [213]: arr.g
Traceback (most recent call last):
  File "<ipython-input-213-b925e810105d>", line 1, in <module>
    arr.g
AttributeError: 'numpy.ndarray' object has no attribute 'g'
  •  Tags:  
  • Related