Python 如何在dataframe中创建一个新列,并对每行中的字符串的一部分进行不同的替换?

Python 如何在dataframe中创建一个新列,并对每行中的字符串的一部分进行不同的替换?,python,pandas,Python,Pandas,我在不同的数据帧中有3个不同的列,如下所示 第1栏有句子模板,例如“他本周想[行动]” 第2栏有成对的单词,例如“锻炼、游泳” 3d列具有单词对的类型,例如[action] 我假设R中应该有类似于“熔化”的东西,但我不确定如何进行替换 我想创建一个新的列/数据框,其中包含每个句子模板的所有可能选项(每行一句话): 这周他想锻炼身体 这周他想游泳 模板的数量明显低于我拥有的单词数量。有几种类型的词对(动作、描述、对象等) 首先使用words['B']中的单词创建新列,然后使用替换值: pat =

我在不同的数据帧中有3个不同的列,如下所示

第1栏有句子模板,例如“他本周想[行动]”

第2栏有成对的单词,例如“锻炼、游泳”

3d列具有单词对的类型,例如[action]

我假设R中应该有类似于“熔化”的东西,但我不确定如何进行替换

我想创建一个新的列/数据框,其中包含每个句子模板的所有可能选项(每行一句话):

这周他想锻炼身体

这周他想游泳

模板的数量明显低于我拥有的单词数量。有几种类型的词对(动作、描述、对象等)


首先使用
words['B']
中的单词创建新列,然后使用替换值:

pat = '|'.join(r"\[{}\]".format(re.escape(x)) for x in words['B'])
templates['matched'] = templates['B'].str.extract('('+ pat + ')', expand=False).fillna('')
templates['repl'] =(templates['matched'].map(words.set_index('B')['A']
                                                  .rename(lambda x: '[' + x + ']'))).fillna('')
print (templates)
   A                                          B   matched            repl
0  1             He wants to [action] this week  [action]  exercise, swim
1  2  She noticed a(n) [object] in the distance  [object]       bus, shop
然后在列表理解中替换:

z = zip(templates['B'],templates['repl'], templates['matched'])
result = pd.DataFrame({'B':[a.replace(c, y) for a,b,c in z for y in b.split(', ')]})
result.insert(0, 'A', result.index + 1)
print (result)
   A                                      B
0  1         He wants to exercise this week
1  2             He wants to swim this week
2  3   She noticed a(n) bus in the distance
3  4  She noticed a(n) shop in the distance

谢谢,我现在就试试!我还添加了代码,用于以与我相同的格式复制输入。只是尝试了一下-这是工作的一部分,但我希望每行只输出一句话(可能在单独的数据帧或列表中)-抱歉,问题中没有明确说明。这对于我的项目的以下步骤是必要的。你认为最好的方法是什么?谢谢:)谢谢,正是我想要的:)
z = zip(templates['B'],templates['repl'], templates['matched'])
result = pd.DataFrame({'B':[a.replace(c, y) for a,b,c in z for y in b.split(', ')]})
result.insert(0, 'A', result.index + 1)
print (result)
   A                                      B
0  1         He wants to exercise this week
1  2             He wants to swim this week
2  3   She noticed a(n) bus in the distance
3  4  She noticed a(n) shop in the distance