【问题标题】:Can't assign value to two cells of a dataframe ValueError: Must have equal len keys and value when setting with an iterable无法为数据帧的两个单元格赋值
【发布时间】: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


    【解决方案1】:

    目前还不清楚您要做什么。话虽如此,我可以通过查看您的代码来提供一些帮助:

    基于希望收入返回两个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)
    

    而不是为每一列分配它。

    【讨论】:

    • 亲爱的@WoIVes。谢谢您的答复。你的假设是对的。我想依次为这两列的每个索引赋值。事实上,我已经在索引范围内编写了一个 for 循环。但是使用这种方法,我不能再将数据框单元格发送到收益函数
    • df.loc[0,['u','u_hat']] = [np.zeros(6),np.zeros(6)];我该如何解决这个问题?
    • 这会产生新的错误stackoverflow.com/q/65967067/3415597
    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2011-01-24
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2012-07-12
    相关资源
    最近更新 更多