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


This Content is from Stack Overflow. Question asked by Haeden

I have a question regarding a transformation I want to add to a Dataframe pandas.
I have a dataframe df with the following columns :

df.columns = Index(['S', 'HZ', 'Z', 'Demand'], dtype='object')

I want to perform the following transformation:

for s in range(S):
   for t in range(HZ):
       for z in range(Z):
          if t > T:
             df.loc((df['S'] == s) & (df['HZ'] == t) & (df['Z'] == z), 'Demand') = D[s][t][z]

Where D is a numpy array with the corresponding dimensions. This code functions, but it is very long, so I tried something else to avoid the for loops :

df.loc[df['HZ'] >= T, 'Demand'] = D[df['S']][df['HZ']][df['Z']]

Which raises the following error :

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

I am searching what this error means, how to fix it if possible, and if not possible, is there a mean to do what I want without using for loops ?

Thanks by advance


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?