无法为dataframe ValueError的两个单元格赋值:使用iterable设置时,必须具有相等的len键和值

2024-04-19 02:05:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了一个包含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”列的值。我编写了一个名为revenue的函数,并为输出传递了两个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

为了澄清,这是revenue函数调用的输出及其类型以及数据帧单元的类型

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")

这是上述代码段的输出:

(array([ 51.7893083 , 84.71773404, 14.27980182, 50.44854285,

-2324.48487998, 113.14393764]), array([ 31.27595156, 21.06329296, 30.25086505, 20.91139397, -46.23146317, 12.72995963]))

type of revenue output is <class 'list'> nd the length of it is 1

type of b is <class 'numpy.ndarray'> nd the length of it is 2

type and length of the df.loc[0,['u','u_hat']] are <class 'pandas.core.series.Series'> and 2 respectively

所以,问题是我既不能将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

Blockquote


Tags: andofthedflenobjectishat
1条回答
网友
1楼 · 发布于 2024-04-19 02:05:34

现在还不清楚你想做什么。也就是说,我可以通过查看您的代码来帮助您:

基于希望revenue返回两个np.arrays和您的df.loc[0,['payoff','power']],我假设您希望将第一行的payoffpower列分别设置为revenue中生成的列表。当前代码将失败,因为您正在获取这两个数组,然后将它们放入一个新列表中,同时仍试图分配给这两列。这可以通过以下方式解决:

df.loc[0,['payoff','power']] = revenue(initialoffer)

假设P是在revenue函数的某个地方定义的,这将解决上面提到的错误代码

但是,请注意,如果从标准索引更改索引,df.loc也可能会填充另一行。因此,如果您只希望第一行有此解决方案,并且只希望第一行有此解决方案,请使用df.iloc

还请注意,只需使用以下命令,就可以更轻松地将所有列分配给object

df = df.astype(object)

而不是为每列指定它

相关问题 更多 >