如何在pandas数据框中创建新列,并用不同的方式替换每一行中的一部分字符串?

阿利纳兹

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

第1列包含句子模板,例如“他想在本周内[采取行动]”。

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

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

我认为R中应该有一些类似于“融化”的东西,但是我不确定如何进行替换。

我想创建一个新的列/数据框,它将为每个句子模板(每行一个句子)提供所有可能的选项:

他本周想锻炼。

他想这周游泳。

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

#a simple example of what I would like to achieve

import pandas as pd

#input1
templates = pd.DataFrame(columns=list('AB'))
templates.loc[0] = [1,'He wants to [action] this week']
templates.loc[1] = [2,'She noticed a(n) [object] in the distance']
templates

#input 2
words = pd.DataFrame(columns=list('AB'))
words.loc[0] = ['exercise, swim', 'action']
words.loc[1] = ['bus, shop', 'object']
words

#output    
result = pd.DataFrame(columns=list('AB'))   
result.loc[0] = [1, 'He wants to exercise this week']
result.loc[1] = [2, 'He wants to swim this week']
result.loc[2] = [3, 'She noticed a(n) bus in the distance']
result.loc[3] = [4, 'She noticed a(n) shop in the distance']
result


耶斯列尔

首先Series.str.extract使用来自的单词创建新列words['B'],然后Series.map使用替换值:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在R中替换数据框中的字符串的一部分?

熊猫:从不同列中的元素替换字符串的一部分

从R中的数据框行中删除字符串的一部分

如何替换pandas.Dataframe中字符串的一部分?

如何在PHP中替换字符串的一部分?

如何在javascript中替换字符串的一部分

如何在 PHP 中隐藏/替换字符串的一部分?

删除数据框列(R)中的一部分字符串

如何用另一行中的单词替换一行中的一部分字符串?

如何在pandas数据框单元格中提取字符串的一部分并创建一个包含该字符串的新列

Pandas Dataframe用另一列中的值替换字符串的一部分

正则表达式使用字符拆分并用不同的字符串替换第一部分

Python 3用dict中的数据替换字符串的一部分

使用列中的一部分字符串来计算并填充pandas数据框中的另一列

提取行名称的一部分以在R中的数据框中创建新列

如何使用通配符在mysql中删除/替换字符串的一部分?

拆分并从列值中取出一部分字符串,然后在 Pandas python 中创建新列

如何在r中重新排序和替换字符串的一部分?

如何从 Python 中的 Pandas DataFrame 中删除字符串的一部分

如何将字符串的一部分从列复制到熊猫的新列中

在CSV中找到字符串的一部分,并用新条目替换整个单元格?

Pyspark - 用不同的字符替换字符串的一部分(字符数不均匀)

如何在JavaScript中的“:”之前删除字符串的一部分?

如何在JavaScript中获取字符串的最后一部分?

如何在recyclerview中隐藏字符串的一部分?

如何在Java中检索字符串的一部分?

如何在JavaScript中删除字符串的最后一部分?

如何在python数组中查找字符串的一部分

如何在laravel 5.2中仅显示字符串的一部分?