gpt4 book ai didi

python - 如何在 pandas 数据框中创建一个新列,并对每行中的字符串部分进行不同的替换?

转载 作者:行者123 更新时间:2023-12-01 07:43:18 25 4
gpt4 key购买 nike

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

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

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

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

我认为 R 中应该有类似于“melt”的东西,但我不知道如何进行替换。

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

他这周想练习。

他这周想游泳。

模板的数量明显少于我的单词数量。单词对有多种类型( Action 、描述、对象等)。

#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

关于python - 如何在 pandas 数据框中创建一个新列,并对每行中的字符串部分进行不同的替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56578870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com