Search code examples
pythonnumpynetworkx

Storing a numpy array within a iteration loop


[Edit] Actually, this is a networkx problem where I is a list of nodes in array format (not in the nx.nodes list) (in networkx); I want to record these 100 sets of nodes as X = { I1,I2,...,I100 } in a file. The file should contain 100 lines and each line should contain the list of nodes infected which are separated by a space. Then afterwards I have to make a graph (actually a subgraph) with each of these list of nodes Ii and find the centre of each of these subgraphs , i.e 100 centres [Edit]

This iteration generates a list of 100 np.arrays of I how to store all these 100 arrays in a variable so that I can use this data later on. Preferably a text file! The following doesn't work!

I_collect = np.zeros(5)

for counter in range(100):
     
    t, S, I = EoN.fast_SIS(g, tau, gamma, tmax = 10, initial_infecteds = 0)
    I_collect(counter) = I;

error:

I_collect(counter) = I;
    ^
SyntaxError: can't assign to function call

Solution

  • @Claudio is correct, but there is another consideration. When you create your np.zeros array, you need to be aware of the shape of the array as you make it, because the calculated arrays need to be commensurate with the dimensions of the storage space.

    For example, if you use your code as is, it will throw an error:(I don't know the length of your solutions or have access to the function so I have an array filled with random numbers)

    import numpy as np
    I_collect = np.zeros(5)
    
    for idx in range(100):
        I = np.random.rand(10)
        I_collect[idx] = I
        
    print(I_collect)
    
    ValueError: setting an array element with a sequence.
    

    The correct way to go about this is to know a priori what the shape you want to use will be. In this case, you loop 100 times, so I assume at least one dimension is going to be of length 100, while the other is not known to me, so I use 10. Then in this example code we get

    import numpy as np
    I_collect = np.zeros((100,10)) # Preallocate an array
    
    for idx in range(100):
        I = np.random.rand(10)
        I_collect[idx] = I
        
    print(I_collect)
    

    Another slower way to go about this if you don't know what shape the array will be, is to just append a list and then convert it to an array as such

    import numpy as np
    I_collect = [] # Append this empty list with values
    
    for idx in range(100):
        I = np.random.rand(10)
        I_collect.append(I)
        
    print(np.array(I_collect))