Home > Mobile >  How work to with an array of arrays and how initialize multiple arrays in Numpy?
How work to with an array of arrays and how initialize multiple arrays in Numpy?

Time:10-08

I have to write an ABM (agent-based model) project in Python and I need to initialize 50 agents which will each contain a different set of numbers. I cannot use a matrix of 50 rows because each agent (each row) can have a different quantity of elements so the vector of each agent has not the same length: when certain conditions for agent_i occur in the algorithm then a number calculated by the algorithm is added to its vector. The simplest way would be to write manually every one like this

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

but of course I can't. I don't know if exist a way to automatically initialize with a loop, something like

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

If it exist, It would be useful because then, when certain conditions occur in the algorithm, I could add a calculated numbers to agent_i:

agent_i = np.append(agent_i, result_of_algorithm)

Maybe another way is to use an array of arrays

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

Once again, I don't know how to initialize an array of arrays and I don't know how to add a number to a specific array: in fact I think it can't be done like this (assume, for simplicity, that I have this little array of only 3 agents and that I know how it is done):

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)

output:

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

why it changes in that way?

Do you have any advice on how to manipulate arrays of arrays? For example, how to add elements to a specific point of a sub-array (agent)?
Thanks.

CodePudding user response:

List of Arrays

You can create a list of arrays:

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

And then to append values to some agent, say agents[0], use:

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

List of Lists

Alternatively, if you don't need to use np.arrays, you can use lists for the agents values. In that case you would initialize with:

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

And you can append to agents[0] with either

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

Or with

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