将一列中的单词与其他列python中的其他单词串联在一起

时间:2019-09-05 06:47:54

标签: python pandas dataframe concatenation

这是数据集

pd.DataFrame({'Word':['Iron','copper','nickel'],'Sentence':['An Apple a day','Roses are red','Skies are blue']})

我正在尝试将一个单词与另一个单词连接在一起,并将其附加到新列中,这样我的输出看起来就像

     Word        Sentence                         New_Sentence
0    Iron  An Apple a day   An_Iron Apple_Iron a_Iron day_Iron
1  copper   Roses are red   Roses_copper are_copper red_copper
2  nickel  Skies are blue  skies_nickel are_nickel blue_nickel

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

首先通过Sentence得到split中的每个单词,然后将Wordf-string s相加:

f = lambda x: ' '.join(f"{y}_{x['Word']}" for y in x['Sentence'].split())
df['New_Sentence'] = df.apply(f, axis=1)
print (df)
     Word        Sentence                         New_Sentence
0    Iron  An Apple a day   An_Iron Apple_Iron a_Iron day_Iron
1  copper   Roses are red   Roses_copper are_copper red_copper
2  nickel  Skies are blue  Skies_nickel are_nickel blue_nickel

或将列表理解与zip一起使用:

zipped = zip(df['Word'], df['Sentence'])
df['New_Sentence'] = [' '.join(f"{y}_{a}" for y in b.split()) for a, b in zipped]

答案 1 :(得分:1)

尝试一下

>>> df['New_Sentence'] = df.apply(lambda x: ' '.join(['_'.join(i) for i in [(s, x['Word'])
                                 for s in x['Sentence'].split()]]), axis=1)

>>> df

     Word        Sentence                         New_Sentence
0    Iron  An Apple a day   An_Iron Apple_Iron a_Iron day_Iron
1  copper   Roses are red   Roses_copper are_copper red_copper
2  nickel  Skies are blue  Skies_nickel are_nickel blue_nickel