where with append within my loop, but I get the error ;
TypeError: can't multiply sequence by non-int of type 'numpy.float64'
example data & preprocessing:
data1 = pd.DataFrame({"cust_id": ['x111'], #customer data
"state": ['B'],
"amount": [1000],
"year":[3],
"group":[10],
"loan_rate":[0.12]})
data1['state'] = pd.Categorical(data1['state'],
categories=state_list,
ordered=True).codes
state_list = ['A','B','C','D','E'] #possible states
lookup1 = pd.DataFrame({'year': [1, 2, 3, 4, 5],
'lim %': [0.1, 0.1, 0.1, 0.1, 0.1]}).set_index(['year'])
matrix_data = np.arange(125).reshape(5,5,5) #3d matrix by state(A-E) and year(1-5)
working loop calculation:
results={}
for cust_id, state, amount, start, group, loan_rate in data1.itertuples(name=None, index=False):
res = [amount * matrix_data[start-1, state, :]]
for year in range(start 1, len(matrix_data) 1,):
res.append(lookup1.loc[year].iat[0] * np.array(res[-1])) #trying to edit this line
res.append(res[-1] * loan_rate)
res.append(res[-1] 60)
res.append([res[-1] @ matrix_data[year-1]])
results[cust_id] = res
Changes I am trying to make:
I am trying to edit this line ;
res.append(lookup1.loc[year].iat[0] * np.array(res[-1]))
to this:
res.append(np.where(np.isin(res,res[-1][0:3])),(lookup1.loc[year].iat[0] * res),res)
as I only want to multiply res[-1][0:3] by the lookup1 value, and the rest of the values in the array remain the same.
example output:
{'x111': [array([55000, 56000, 57000, 58000, 59000]),
array([ 5500., 5600., 5700., 58000., 59000.]),...
CodePudding user response:
You're looking at the problem wrong.
Just make lookup1.loc[year].iat[0]
an np.array
too.
results={}
for cust_id, state, amount, start, group, loan_rate in data1.itertuples(name=None, index=False):
res = [amount * matrix_data[start-1, state, :]]
for year in range(start 1, len(matrix_data) 1,):
temp = np.array([lookup1.loc[year].iat[0]]*len(matrix_data))
temp[3] = temp[4] = 1
res.append(temp * np.array(res[-1])) #trying to edit this line
res.append(res[-1] * loan_rate)
res.append(res[-1] 60)
res.append([res[-1] @ matrix_data[year-1]])
results[cust_id] = res