0

I have a df:

    a   b       c
0  'd'  1  ['f', 'h']
1  'f'  2  ['u', 'v']
2  'g'  3  ['i', 'o']

I want to append df['a'] to each element of df['c'] column. expected output:

    a   b       c          d
0  'd'  1  ['f', 'h']  ['fd', 'hd']
1  'f'  2  ['u', 'v']  ['uf', 'vf']
2  'g'  3  ['i', 'o']  ['ig', 'og']

I tried for loops, and an attempt at list comprehension, but it was garbage. To avoid for loops, I have tried this vectorized approach. But did not work.

df['d']=df['c'].cat(df['a'],axis=0).values.tolist()

As always, any help, much appreciated.

2
  • That is not a correct representation of a list of strings. The strings should be enclosed in paranthesis, like ['f', 'h'] Commented Dec 19, 2020 at 14:00
  • yes. sorry for wrong representation. please find the update now. Commented Dec 19, 2020 at 14:03

1 Answer 1

2

We can use explode to unnest your list, then add the strings together and finally use groupby on the index and use agg(list) to get your list back:

ex = df.explode('c')
ex['c'] = ex['c'] + ex['a']

df['c'] = ex.groupby(ex.index)['c'].agg(list)
   a  b         c
0  d  1  [fd, hd]
1  f  2  [uf, vf]
2  g  3  [ig, og]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.