Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

loop through dataframe and assign values based on previous row

import pandas as pd
test = pd.DataFrame({'Country':['USA','USA','USA','USA','USA'],
             'Month':[6,7,8,9,10],
              'Sales':[100,200,0,0,0],
              'Recovery':[0,1,1.5,2.5,3]
             })

test['Prediction'] = test['Sales']
for i in range(1, len(test)):
    #prevent division by zero
    if test.loc[i-1, 'Recovery'] != 0:
        test.loc[i, 'Prediction'] = test.loc[i-1, 'Prediction'] * test.loc[i, 'Recovery'] / test.loc[i-1, 'Recovery']
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #loop #dataframe #assign #values #based #previous #row
ADD COMMENT
Topic
Name
5+6 =