Search code examples
pythonarraysfor-loopnestedcell-array

Store the result of nested for loop iteration in a single variable: A table with multiple columns of different lengths


I am trying to generate random numbers between 0 and 1 for each MONTH OF A YEAR: e.g. January has 31 days, I want to generate 31*24 numbers of such random numbers and store them in an array. Same for each of the 12 months. I want them all to be stored under the same table or matrix, which can be called for further operation. In MATLAB this is achieved easily by storing the for loop results in a cell-array. I want to do the same in Python. If I append all the random numbers they just create a loooooong array (1D), but I would prefer an array with 12 columns 1 for each month, where the random numbers are stored vertically. As the number of days for each month is different, the length of each month column will be different.

# Find the no of hours in each month in a certain year
import calendar
k = 1
hrs = np.array([])
for k in range(12):
    no_hrs = (calendar.monthrange(2020, k+1) [1])*24 # 2020 is a random year
    hrs = np.append(hrs,no_hrs)
hrs = hrs.astype(int) # no of hrs for each month
# Now we generate the random numbers and store them in an 1D array
rndm = np.array([])
k = 1
for k in range(12):
    for _ in range(hrs[(k)]):
        value = random()
        rndm = np.append(value,rndm)
    rndm # this is the array containing 366*24 elements (for a year)
# But I would like the array to be splitted in months

The array will contain 366*24 = 8784 elements (for a year) But I would like the array to be split in months. (Unequal column size)


Solution

  • It can be done using list of np.arrays I added print of length of each array.

    import calendar
    import numpy as np
    import random
    
    k = 1
    hrs = np.array([])
    for k in range(12):
        no_hrs = (calendar.monthrange(2020, k+1) [1])*24 # 2020 is a random year
        hrs = np.append(hrs,no_hrs)
    hrs = hrs.astype(int) # no of hrs for each month
    
    rndm = []
    k = 1
    for k in range(12):
        x =  np.array([])
        for _ in range(hrs[(k)]):
            value = random.random()
            x = np.append(value,x)
        rndm.append(x)
    
    print(len(rndm))
    for k in range(12):
        print(k, len(rndm[k]))
    

    and it prints

    12
    0 744
    1 696
    2 744
    3 720
    4 744
    5 720
    6 744
    7 744
    8 720
    9 744
    10 720
    11 744
    

    You can use dictionaries if you want to have month names not numbers.