В словаре python почему он хранит только взамен последнее вычисленное значение - PullRequest
0 голосов
/ 19 апреля 2020

Я пытаюсь создать функцию, которая возвращает словарь python с различными результатами, полученными при моделировании, но она всегда возвращает только последнее вычисленное значение в словаре, но когда я запускаю код вне функции, она возвращает все значения в словаре. Я хотел бы знать, как вернуть в словарь все вычисленные значения.

def calcular_pr(datos_meses,datos_final,groupsY,number_of_simulations):

"""
Parameters
----------
datos_final : DataFrame
    Example of input data of datos_final
    Date    Datos
    1/1/1962    54
    1/2/1962    20
    1/3/1962    0
    1/4/1962    0
    1/5/1962    0
    1/6/1962    0
    1/7/1962    2
    1/8/1962    0
    1/9/1962    0
    1/10/1962   0
    1/11/1962   0
    1/12/1962   5
    1/13/1962   0
    1/14/1962   0
    1/15/1962   49

datos_meses : DataFrame
    Example of input data of datos_meses
    Date    Datos
    1/31/1962   138
    2/28/1962   174
    3/31/1962   149
    4/30/1962   320

groupsY : DataFrame
    Example of input data of groupsY
    Date    Datos   year
    12/31/1962  365 1962
    12/31/1963  365 1963
    12/31/1964  366 1964

number_of_simulations : int
    Amount of simulations to do

Returns
-------
dict_Simulaciones : Dictionary of DataFrames

dict_datos_meses_Gen : Dictionary of DataFrames

dict_mean_gen : Dictionary of Numpy array

"""

#Creates the dictionaries
dict_Simulaciones = {}
dict_datos_meses_Gen = {}
dict_mean_gen = {}


for p in range(0,number_of_simulations):

    #Creates the array for the calculations
    preciCalc = np.array([])

    for i in groupsY['year']:

       #month_to_day is another function 
       preciCalc = np.append([[preciCalc]],[[month_to_day(datos_meses.loc[( datos_meses.index.year==i)],i, datos_final)]])

    #Resets the index
    datos_final.reset_index(inplace=True)
    #From numpy array to pandas dataframe
    preciCalc = pd.DataFrame(data=preciCalc.flatten(), columns = ['Datos'])
    #Use same index for the dates
    preciCalc.index = datos_final.index
    #Copy the column date from the original data
    preciCalc[['Date']] = datos_final[['Date']]
    #Set Index Date
    preciCalc.set_index('Date', inplace=True)
    #Set Index Date
    datos_final.set_index('Date', inplace=True)

    """
       preciCalc example results are as shown below
        Date    Datos
        1/1/1962    45.55210047
        1/2/1962    11.11451802
        1/3/1962    3.735904344
        1/4/1962    11.29685609
        1/5/1962    8.290304
        1/6/1962    5.283751914
        1/7/1962    2.436745634
        1/8/1962    1.275859957
        1/9/1962    2.299992086
        1/10/1962   4.147684473
        1/11/1962   8.652954151
        1/12/1962   2.915383054
        1/13/1962   2.026484989
        1/14/1962   0.728845763
        1/15/1962   0.47243286
       """

    # Sum of the complete months
    downsample = preciCalc.resample('M').sum()

    #Reset index
    downsample.reset_index(inplace=True)
    #Generate the list accumulator
    datos_meses_Gen = []
    #for loop that loops over the years with complete days of data
    for k in groupsY['year']:
        #for loop to loop over the index in the df datos
        for j in range(len(downsample)):
            #if to compare if the years with data complete is in the df datos
            if k == downsample.Date[j].year:
                #use the list accumulator when the if statement is true
                datos_meses_Gen.append([downsample.Date[j], downsample.Datos[j]])
    #Convert the list into a dataframe
    datos_meses_Gen = pd.DataFrame(datos_meses_Gen, columns = ['Date','Datos'])

    #Puts the datetime index
    datos_meses_Gen.set_index('Date', inplace=True)

    dict_Simulaciones[p] = preciCalc
    dict_datos_meses_Gen[p] = datos_meses_Gen

    # mean of Generated data
    meanGen = np.array([])

    #Calculate the statistics
    for a in range(1,13):
        meanGen = np.append([[meanGen]],[[np.mean(dict_datos_meses_Gen[p].loc[(dict_datos_meses_Gen[p].index.month==a)])]])
    dict_mean_gen[p] = meanGen            

    return (dict_Simulaciones, dict_mean_gen)  

Это результат, который я хочу получить

Это то, что я получаю с моим текущим кодом

...