Skip to content
Advertisement

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

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

JavaScript

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

JavaScript

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:

JavaScript

Maybe another way is to use an array of arrays

JavaScript

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):

JavaScript

output:

JavaScript

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.

Advertisement

Answer

List of Arrays

You can create a list of arrays:

JavaScript

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

JavaScript

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:

JavaScript

And you can append to agents[0] with either

JavaScript

Or with

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement