Issue
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
Solution
After trying many things, I finally found something that works :
df.loc[df['HZ'] >= T, 'Demand'] = D[df.loc[df['HZ'] >= T, 'S']][df.loc[df['HZ'] >= T, 'HZ'] - T][df.loc[df['HZ'] >= T, 'Z']]
The problem is that with this line :
df.loc[df['HZ'] >= T, 'Demand'] = D[df['S']][df['HZ']][df['Z']]
I try to access the elements of D with series (df['S']
for example), which represent columns of the dataframes, and this is not possible. With the solution I found, I access the value of the column I wanted to locate the corresponding element of D.
This Question was asked in StackOverflow by Haeden and Answered by Haeden It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.