pythonnumpymontecarlotriangular

Monte Carlo simulation from a triangular distribution in Python


I'm new to python and trying to use the numpy.random triangular function to run a series of Monte Carlo simulations from several triangular distributions and then append the simulation outputs from each run. The sample data is as below.

ID  Low  Mode  High  
A   10   15    25
B   7    20    22
C   2    18    20
D   1    4     5
E   13   25    34

I would like to run 10000 runs for each ID and append the results. I know I can run for each ID for example ID A using np.random.triangular(10, 15, 25, 10000). May need to write for loop to run and append all IDs. Thank you!

Update!

The expected output format is:

ID Run      Output
A   1       11
A   2       23
.
.
.
A   10000   18
B   1       21.5
B   2       9
.   .       .
.   .       .
.   .       .
B   10000   19
C   1       2.5
C   2       13
.   .       .
.   .       .
.   .       .

Solution

  • df is a dataframe with your data and in the cycle I am iterating through the rows, so basically each row of the new dataframe will have an array with the 10000 samples.

    import pandas as pd
    import numpy as np
    Low = [10,7,2,1,13]
    Mode = [15,20,18,4,25]
    High = [25,22,20,5,34]
    ID = ['A', 'B', 'C', 'D', 'E']
    df = pd.DataFrame(zip(Low, Mode, High), columns = ['Low', 'Mode', 'High'], index = ID)
    cols = ['Output']
            
    df2 = pd.DataFrame(columns=cols, index = ID)
    
    for l in range(5):
        result = np.random.triangular(df.iloc[l][0], df.iloc[l][1], df.iloc[l][2], 10000)
        df2.iloc[l][0] = result
    

    An example of the output:

    enter image description here