Home > Software design >  Looping through a list and adding value to new dataframe column
Looping through a list and adding value to new dataframe column

Time:02-23

First time posting here so I apologize in advance if the formatting of my post is off:

I'm trying to loop through the following list called "result"

result=[60, 145, 195, 275, 525, 560, 645, 720, 905, 1020, 1315, 1440, 1610, 1860, 1940, 2740,3190, 3387]

each of these values is essentially the index or x_value to a y_value, called "points" which is in the form of an array

points= [0.039612  0.0393142 0.0395416 ... 0.0380617 0.0379095 0.0379999]

I have the result value as the index in a new dataframe and was trying to loop though the results list (except the last value) above and to return the corresponding "points" array value in the points column. However the for loop I currently have set up just returns the final "points" value for all rows in the column so it's clearly being overwritten. Also note, that only select values of the array are being selected.

for i in result[:-1]:
    df2[i:1]=points[i]

         points
result  
60      0.038062
145     0.038062
195     0.038062
275     0.038062
525     0.038062
560     0.038062
645     0.038062
720     0.038062
905     0.038062
1020    0.038062
1315    0.038062
1440    0.038062
1610    0.038062
1860    0.038062
1940    0.038062
2740    0.038062
3190    0.038062

Can someone please point me in the right direction?

thanks

CodePudding user response:

Assuming points is a numpy array, instead of the loop, try this:

df2[1:] = points[result[:-1]]
  • Related