Prevent Pandas from unpack list in value assignation

Viewed 103

Starting from dataframe df, I would like to apply dictionary dict as translation table and create another column with translated results:

input:

df=pd.DataFrame({'A': 'foo bar one123 bar foo one324 foo 0'.split(),
'B': 'one546 one765 twosde three twowef two234 onedfr three'.split(),
'C': 'lol'})

output:

     A       B       C
0   foo    one546   lol
1   bar    one765   lol
2   one123 twosde   lol
3   bar    three    lol
4   foo    twowef   lol
5   one324 two234   lol
6   foo    onedfr   lol
7   0      three    lol

replacement dictionary:

dict={'foo':['blue'],'bar':['red'],'one123':['purple','green']}

For each occurrance of a key of dict in column "A", I would like to assign value of dict to a new column "D". Notice that some value of dict are list with one or two elements.

for key,value in dict.items():
    df.loc[df['A']==key,'D']=[value]

I tried with and without square bracket on value, so value and [value] but the result is always:

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

I noticed that if I put df.loc[df['A']==key,'D']=value, so without square brackets around value, I obtain the error before the first substitution, while if I use square brackets, the error appears before the last element ['purple','green'], so the list with two elements.

How can I prevent pandas from trying to unpack the list and just use value as it is? Thank you for the kind answer

0 Answers
Related