简体   繁体   English

append 与列 pandas 中的字符串列表相同的字符串

[英]append same string to list of strings in a column pandas

I have a df:我有一个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.我想 append df['a'] 到 df['c'] 列的每个元素。 expected output:预期 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.我尝试了 for 循环,并尝试了列表理解,但它是垃圾。 To avoid for loops, I have tried this vectorized approach.为了避免 for 循环,我尝试了这种矢量化方法。 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:我们可以使用explode来取消您的列表,然后将字符串添加在一起,最后在索引上使用groupby并使用agg(list)来获取您的列表:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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