![](/img/trans.png)
[英]Python: I keep getting a broadcasting error, but I'm not sure how to fix it
[英]How to fix value error broadcasting in python loop?
我无法修复我的广播错误,我得到的当前错误是ValueError: operands could not be broadcast together with shapes (10,) (5,)
预处理数据:
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, 6, 7, 8, 9, 10],
'lim %': [0.1, 0.1, 0.1, 0.1, 0.1,0.1, 0.1, 0.1, 0.1, 0.1]}).set_index(['year'])
matrix_data = np.arange(250).reshape(10,5,5) #3d matrix by state(A-E) and year(1-10)
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
预期 output:
{'x111': [array([55000, 56000, 57000, 58000, 59000]),
array([ 5500., 5600., 5700., 58000., 59000.]),...
看看下面的代码片段是否适合您,并根据您的方便进行更改:
import pandas as pd
import numpy as np
state_list = ['A','B','C','D','E'] #possible states
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
lookup1 = pd.DataFrame({'year': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'lim %': [0.1, 0.1, 0.1, 0.1, 0.1,0.1, 0.1, 0.1, 0.1, 0.1]}).set_index(['year'])
matrix_data = np.arange(250).reshape(10,5,5) #3d matrix by state(A-E) and year(1-10)
results={}
for cust_id, state, amount, start, group, loan_rate in data1.itertuples(name=None, index=False):
print(cust_id, state, amount, start, group, loan_rate)
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[:5] * 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
print(results)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.