numpy对象数组 [英] numpy array of objects
问题描述
我正在尝试在Python中实现对晶格模型(lattice boltzmann)的仿真.晶格的每个位置都具有许多属性,并根据某些规则与相邻位置进行交互.我认为用一个具有所有属性的类并对该类的实例进行网格处理可能是明智的. (由于我对Python缺乏经验,所以这可能根本不是一个好主意,因此请随时对我的方法发表评论.)
I'm trying to implement a simulation for a lattice model (lattice boltzmann) in Python. Each site of the lattice has a number of properties, and interact with neighboring sites according to certain rules. I figured that it might be clever to make a class with all the properties and make a grid of instances of that class. (As I'm inexperienced with Python, this might not be a good idea at all, so feel free to comment on my approach.)
这是我在做什么的一个玩具例子
Here is a toy example of what I'm doing
class site:
def __init__(self,a,...):
self.a = a
.... other properties ...
def set_a(self, new_a):
self.a = new_a
现在,我想处理此类站点的2D/3D网格(网格),因此我尝试执行以下操作(这里以2D 3x3网格为例,但是在仿真中,我需要> 1000x1000X1000的顺序)
Now I want to deal with a 2D/3D lattice (grid) of such sites so I tried to do the following (here is a 2D 3x3 grid as an example, but in simulation I would need the order of >1000x1000X1000)
lattice = np.empty( (3,3), dtype=object)
lattice[:,:] = site(3)
现在,问题在于每个晶格点都引用相同的实例,例如
Now, the problem is that each lattice point refer to the same instance, for example
lattice[0,0].set_a(5)
还将将grid [0,2] .a的值设置为5.这种行为是不希望的.为避免该问题,我可以遍历每个网格点并逐个元素地分配对象,例如
will also set the value of lattice[0,2].a to 5. This behavior is unwanted. To avoid the problem i can loop over each grid point and assign the objects element by element, like
for i in range(3):
for j in range(3):
lattice[i,j] = site(a)
但是还有更好的方法(不涉及循环)将对象分配给多维数组吗?
But is there a better way (not involving the loops) to assign objects to a multidimensional array?
谢谢
推荐答案
您可以 vectorize 该类的__init__
函数:
import numpy as np
class Site:
def __init__(self, a):
self.a = a
def set_a(self, new_a):
self.a = new_a
vSite = np.vectorize(Site)
init_arry = np.arange(9).reshape((3,3))
lattice = np.empty((3,3), dtype=object)
lattice[:,:] = vSite(init_arry)
这看起来更干净,但与循环解决方案相比没有任何性能优势.列表理解答案会创建一个中间python列表,这会导致性能下降.
This may look cleaner but has no performance advantage over your looping solution. The list comprehension answers create an intermediate python list which would cause a performance hit.
这篇关于numpy对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!