合并熊猫中的两个字符串列表

时间:2019-07-09 01:03:50

标签: python pandas

我有一个带有两个x和y序列的数据框。我想将它们合并以创建一个新的series:标签,但是我无法实现预期的输出。我尝试过:

df['tag'] = df['x'] + df['y']

我到处都是,却找不到解决问题的方法。

当前输出:

x                               y           tag
['fast food', 'american']   ['chicken'] ['fast food', 'american']['chicken']

预期输出:

x                               y           tag
['fast food', 'american']   ['chicken'] ['fast food', 'american', 'chicken']

df.to_dict()

{'x': "['fast food', 'american']",
 'y': "['chicken']"}

4 个答案:

答案 0 :(得分:2)

我不认为这是mainSlider = { initialSlide: 0, speed: 1500, direction: 'vertical', // allowSlideNext: false - this param only work to block sliders to go next but can't go prev anymore in the other sliders, so I just want to apply this method to block the first slide to stop showing the outside looking animation, but unfortunately I didn't succeed in this }; ,因此您可以将其转换为list,他们可以list

sum

更多信息

import ast
df.x = df.x.apply(ast.literal_eval)
df.y = df.y.apply(ast.literal_eval)

df['tag'] = df['x'] + df['y']

答案 1 :(得分:0)

另一种方法是使用re.findall

import re

df.applymap(lambda x:re.findall("'(.+?)'", x)).sum(1)

将返回list中的str

                           x            y                             tag
0  ['fast food', 'american']  ['chicken']  [fast food, american, chicken]

答案 2 :(得分:0)

您可以解压缩列表,然后使用Apply创建新列。 enter image description here

答案 3 :(得分:-1)

已更新

尝试一下:

df=pd.DataFrame()
df['X']=[["chicken"]]
df['Y']=[["fast food","American"]]
df['tag']=df['X']+df['Y']