Consider df
A B C
0 3 2 1
1 4 2 3
2 1 4 1
3 2 2 3
I want to add another column "D"
such that D contains different Lists based on conditions on "A"
, "B"
and "C"
A B C D
0 3 2 1 [1,0]
1 4 2 3 [1,0]
2 1 4 1 [0,2]
3 2 2 3 [2,0]
My code snippet looks like:
df['D'] = 0
df['D'] = df['D'].astype(object)
df.loc[(df['A'] > 1) & (df['B'] > 1), "D"] = [1,0]
df.loc[(df['A'] == 1) , "D"] = [0,2]
df.loc[(df['A'] == 2) & (df['C'] != 0) , "D"] = [2,0]
When I try to run this code it throws the following error:
ValueError: Must have equal len keys and value when setting with an iterable
I have converted the column into Object
type as suggested here but still with error.
What I can infer is that pandas is trying to iterate over the elements of the list and assigns each of those values to the cells where as I am trying to assign the entire list to all the cells meeting the criterion.
Is there any way I can assign lists in the above fashion?