首页 > 解决方案 > 将一列的单词与其他列python中的所有其他单词连接起来

问题描述

这是数据集

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

有什么建议么?

标签: pythonpandasdataframeconcatenation

解决方案


尝试这个,

>>> 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

推荐阅读