anjali
anjali

Reputation: 47

append same string to list of strings in a column pandas

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.

Upvotes: 0

Views: 258

Answers (1)

Erfan
Erfan

Reputation: 42886

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]

Upvotes: 2

Related Questions