简体   繁体   中英

Can't assign value to two cells of a dataframe ValueError: Must have equal len keys and value when setting with an iterable

I have defined a dataframe with 5 columns:

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)

At the beginning, the values of the cells are NaN. Then, in a part of my code I want to set the values of the columns 'payoff' and 'power'. I have written a function whose name is revenue and passes two numpy arrays for the output

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

This is how I am assigning value to the dataframe:

initialoffer = [2,  5,  1 ,  3,  50,  10];
df.loc[0,['payoff','power']] = [revenue(initialoffer)]

But, I receive the following error:

 ValueError: Must have equal len keys and value when setting with an iterable

To clarify, this is the output of the revenue function call and its type as well as type of dataframe cells

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

This is the output of the above snippet:

(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

So, the problem is that I can pass neither a nor b to the desired cells. df.loc[0,['u','u_hat']]=b or

df.loc[0,['u','u_hat']]=a

Both of the above options gives the following error

ValueError: Must have equal len keys and value when setting with an ndarray

Blockquote

It is very unclear what you are trying to do. That being said, I can help a little just by looking at your code:

Based on wanting revenue to return two np.arrays and your df.loc[0,['payoff','power']] I am assuming you want to set the first row's payoff and power columns to those lists generated in revenue respectively. Your current code will fail as you are taking those two arrays and then putting them into a new list, while still trying to assign to the two columns. This can be resolved as such:

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

This will resolve the error code you mentioned above, assuming that P is defined somewhere in your revenue function.

However, note that if you change your index from the standard index, df.loc may also fill in a different line. Thus if you only want the first row to have this solution and only the first row ever, use df.iloc .

Also note that it is possible to assign all columns to object more easily with just:

df = df.astype(object)

as opposed to assigning it for each column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM