Skip to content
Advertisement

Storing outputs from input parameters into the rows of a panda data frame

I have a list containing values that I want to perform mathematical operations on with different input parameters that are also stored in a list. For each value in the list, I want to store the results from performing the operation – with each distinct input parameter – row-by-row, where each row corresponds to the subsequent input parameter in the list. Here is a minimal reproducible example of my code:

N = 2 #number of rows
index = []

for i in range(N):
    index.append(i)
       
df = pd.DataFrame(columns=['Events','Electrons','Photons'], index=index)

vals = [1,2,3]

param = [1,2]

for idx in df.index:

    df['Events'] = param[idx] + vals[0]

    df['Electrons'] = param[idx] + vals[1]

    df['Photons'] = param[idx] + vals[2]

All this code currently does for me is add param[1] to each element in vals and stores them into each of my two specified rows. What I want is to add param[0] to each element in vals, store and save it to the first row of my data frame, then step forward with param[1], store it in the second row, etc…

Eventually, I want to apply this to a much larger data set with more input parameters, but for now I would just like to know how I can best accomplish this task before scaling it up. Any guidance or advice is greatly appreciated!

Advertisement

Answer

The intent is unclear, but does this do what you want?

param = [1, 2]
vals = [1, 2, 3]

df = pd.DataFrame(columns=["Events", "Electrons", "Photons"], index=range(len(param)))

for i, p in enumerate(param):
    df.iloc[i, :] = np.array(vals) + p

df:
  Events Electrons Photons
0      2         3       4
1      3         4       5

Advertisement