【发布时间】:2021-01-29 18:18:08
【问题描述】:
我定义了一个包含 5 列的数据框:
df = pd.DataFrame(columns=['time','u', 'u_hat', 'payoff','power'], index=range(N))
df['u'] = df['u'].astype(object)
df['u_hat'] = df['u_hat'].astype(object)
df['payoff'] = df['payoff'].astype(object)
df['power'] = df['power'].astype(object)
一开始,单元格的值为NaN。然后,在我的代码的一部分中,我想设置“payoff”和“power”列的值。我写了一个函数,它的名字是收入,并为输出传递了两个 numpy 数组
def revenue(offer):
#some definitions of variables,
# J and P are ndarrays
J = (-alpha_net*(P**2) - (beta_net - offer)*P - gamma_net);
return J,P
这就是我为数据框赋值的方式:
initialoffer = [2, 5, 1 , 3, 50, 10];
df.loc[0,['payoff','power']] = [revenue(initialoffer)]
但是,我收到以下错误:
ValueError: Must have equal len keys and value when setting with an iterable
为了澄清,这是收益函数调用的输出及其类型以及数据框单元格的类型
a = revenue(initialoffer)
print(a)
print("\n type of revenue output is",type([revenue(initialoffer)]),"\and the length of it is", len(([revenue(initialoffer)])))
b= np.asanyarray(a,dtype=object)
print("\n type of b is",type(b),"\and the length of it is", len(b))
print("\n type and length of the df.loc[0,['u','u_hat']] are", type(df.loc[0,['u','u_hat']])," and ",len(df.loc[0,['u','u_hat']]), "respectively")
这是上面sn-p的输出:
(数组([ 51.7893083 , 84.71773404, 14.27980182, 50.44854285,
-2324.48487998, 113.14393764]), 数组([ 31.27595156, 21.06329296, 30.25086505, 20.91139397, -46.23146317, 12.72995963]))
收益输出类型为
长度为1 b 的类型是
并且它的长度是 2 df.loc[0,['u','u_hat']]的类型和长度是
和 2 分别
所以,问题是我不能将 a 和 b 传递给所需的单元格。 df.loc[0,['u','u_hat']]=b 或
df.loc[0,['u','u_hat']]=a
以上两个选项都会出现以下错误
ValueError: Must have equal len keys and value when setting with an ndarray块引用
【问题讨论】:
标签: python pandas dataframe numpy