如何使用数组的数组以及如何初始化Numpy中的多个数组?



我必须在Python中编写一个ABM(基于代理的模型)项目,我需要初始化50个代理,每个代理将包含一组不同的数字。我不能使用50行的矩阵,因为每个代理(每行)可以有不同数量的元素,所以每个代理的向量长度不相同:当算法中出现agent_i的某些条件时,算法计算出的一个数字被添加到其向量中。最简单的方法是像这样手动编写每个

agent_1 = np.array([])
agent_2 = np.array([])
agent_3 = np.array([])
...

但我当然不能。我不知道是否存在用循环自动初始化的方法,比如

for i in range(50):
agent_i = np.array([])

如果它存在,它将是有用的,因为当算法中出现某些条件时,我可以将计算过的数字添加到agent_i:

agent_i = np.append(agent_i, result_of_algorithm)

也许另一种方法是使用数组的数组

[[agent_1_collection],[agent_2_collection], ... , [agent_50_collection]]

再一次,我不知道如何初始化数组的数组,我不知道如何添加一个数字到一个特定的数组:事实上,我认为它不能这样做(假设,为了简单起见,我有一个只有3个代理的小数组,我知道它是如何完成的):

vect = np.array([[1],[2,3],[4,5,6]])
result_of_algorithm_for_agent_2 = ...some calculations that we assume give as result... = 90 
vect[1] = np.append(vect[1], result_of_algorithm_for_agent_2)

输出:

array([[1], array([ 2,  3, 90]), [4, 5, 6]], dtype=object)

为什么会这样变化?

你对如何操作数组的数组有什么建议吗?例如,如何将元素添加到子数组(代理)的特定点?
谢谢。

List of Arrays

你可以创建一个数组列表:

agents = [np.array([]) for _ in range(50)]

然后要向某个代理追加值,例如agents[0],使用:

items_to_append = [1, 2, 3]  # Or whatever you want.
agents[0] = np.append(agents[0], items_to_append)

List of Lists

或者,如果您不需要使用np.array,您可以为代理值使用列表。在这种情况下,你会初始化:

a = [[] for _ in range(50)]

可以在agents[0]后面加上

single_value = 1  # Or whatever you want.
agents[0].append(single_value)

items_to_append = [1, 2, 3]  # Or whatever you want
agents[0] += items_to_append

最新更新