gpt4 book ai didi

python - 将一列中的文本替换为另一列中的字典

转载 作者:行者123 更新时间:2023-12-01 06:51:50 24 4
gpt4 key购买 nike

我的一列中有文本,另一列有相应的字典。我已经对文本进行了标记,并希望替换那些在相应字典中找到与键匹配的标记。文本和字典特定于 pandas 数据帧的每个记录。

import pandas as pd

data =[['1','i love mangoes',{'love':'hate'}],['2', 'its been a long time we have not met',{'met':'meet'}],['3','i got a call from one of our friends',{'call':'phone call','one':'couple of'}]]

df = pd.DataFrame(data, columns = ['id', 'text','dictionary'])

输出的最终数据帧应该是

data =[['1','i hate mangoes'],['2', 'its been a long time we have not meet'],['3','i got a phone call from couple of of our friends']
df = pd.DataFrame(data, columns =['id, 'modified_text'])

我在 Windows 机器上使用 Python 3

最佳答案

您可以在压缩 2 列并分割句子后使用 dict.get 方法:

df['modified_text']=([' '.join([b.get(i,i) for i in a.split()]) 
for a,b in zip(df['text'],df['dictionary'])])
print(df)
<小时/>

输出:

id                                  text  \
0 1 i love mangoes
1 2 its been a long time we have not met
2 3 i got a call from one of our friends

dictionary \
0 {'love': 'hate'}
1 {'met': 'meet'}
2 {'call': 'phone call', 'one': 'couple of'}

modified_text
0 i hate mangoes
1 its been a long time we have not meet
2 i got a phone call from couple of of our friends

关于python - 将一列中的文本替换为另一列中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58953344/

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