简体   繁体   中英

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM