簡體   English   中英

如何使用vectorize為numpy-array中的對象賦值

[英]How to assign values to objects in numpy-array using vectorize

我是python的初學者,我編寫了這段代碼來創建一個二維的numpy對象數組來模擬一個物理點陣。

    import numpy as np  

    class Site:
       def __init__(self, label, status):
          self.l = label
          self.s = status

     vSite = np.vectorize(Site(0,2), otypes=[object])
     init_array = np.arange(25).reshape((5,5))
     lattice = np.empty((5,5), dtype=object)
     lattice[:,:] = vSite(init_array)

但我的輸出有誤

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-0c0dfed8eab8> in <module>()
      9 init_array = np.arange(25).reshape((5,5))
     10 lattice = np.empty((5,5), dtype=object)
---> 11 lattice[:,:] = vSite(init_array)

~/.local/lib/python3.5/site-packages/numpy/lib/function_base.py in __call__(self, *args, **kwargs)
   2753             vargs.extend([kwargs[_n] for _n in names])
   2754 
-> 2755         return self._vectorize_call(func=func, args=vargs)
   2756 
   2757     def _get_ufunc_and_otypes(self, func, args):

~/.local/lib/python3.5/site-packages/numpy/lib/function_base.py in _vectorize_call(self, func, args)
   2823             res = func()
   2824         else:
-> 2825             ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
   2826 
   2827             # Convert args to object arrays first

~/.local/lib/python3.5/site-packages/numpy/lib/function_base.py in _get_ufunc_and_otypes(self, func, args)
   2770                 ufunc = self._ufunc
   2771             else:
-> 2772                 ufunc = self._ufunc = frompyfunc(func, len(args), nout)
   2773         else:
   2774             # Get number of outputs and output types by calling the function on

TypeError: function must be callable

有人可以幫幫我嗎?

np.vectorize()函數必須將函數作為第一個參數,而不是公共變量。 然后,可以在numpy數組上調用它被調用的函數,以將其應用於數組的每個元素。

如果要初始化3D numpy數組,則應使用np.empty(dim)函數,如下所示:

a=np.empty((n,m,l), dtype=object)

該數組將具有n * m * l值。
然后,您可以使用循環遍歷矩陣以填充它:

for i in np.ndindex(a.shape):
    a[i] = Site(1,1)

我發現np.frompyfunc是創建自定義類數組的最佳工具。 你使用np.vectorize也有效,因為你指定了otypes ,但是frompyfunc已經返回了對象,並且更直接,更快。

In [667]: class Site: 
     ...:        def __init__(self, label, status): 
     ...:           self.l = label 
     ...:           self.s = status 
     ...:        def __repr__(self):   # to improve display
     ...:            return f'Site({self.l},{self.s})' 
     ...:                                                                            
In [668]: f = np.frompyfunc(Site, 2,1)                                               
In [669]: f(np.zeros((2,3),int), np.ones((2,3),int)*2)                               
Out[669]: 
array([[Site(0,2), Site(0,2), Site(0,2)],
       [Site(0,2), Site(0,2), Site(0,2)]], dtype=object)
In [670]: f(np.arange(3),np.array(['a','b','c']))                                    
Out[670]: array([Site(0,a), Site(1,b), Site(2,c)], dtype=object)

我應該警告你,雖然訪問這些Site對象也需要使用frompyfunc 對象數組不能充分利用numpy計算速度。 使用數字而不是對象時, numpy計算最快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM