用字典脚本导入txt文件并应用到dataframe替换单词

2024-04-29 03:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用txt文件替换数据帧中某列中的某些字符串。你知道吗

我有一个如下所示的数据帧(这是我拥有的大量数据帧的一个非常小的版本)。你知道吗

coffee_directions_df

Utterance                         Frequency   

Directions to Starbucks           1045
Directions to Tullys              1034
Give me directions to Tullys      986
Directions to Seattles Best       875
Show me directions to Dunkin      812
Directions to Daily Dozen         789
Show me directions to Starbucks   754
Give me directions to Dunkin      612
Navigate me to Seattles Best      498
Display navigation to Starbucks   376
Direct me to Starbucks            201

DF显示了人们的话语和话语的频率。你知道吗

也就是说,“星巴克方向”被说了1045次。你知道吗

我还有一个xlsx格式的数据帧coffee_donut.xlsx,我想用它来导入和替换某些字符串(类似于Replace words by checking from pandas dataframe所要求的)。你知道吗

coffee_donut

Token              Synonyms

Starbucks          Coffee
Tullys             Coffee
Seattles Best      Coffee
Dunkin             Donut
Daily Dozen        Donut

最后,我希望数据帧看起来像这样:

coffee_donut_df

Utterance                        Frequency   

Directions to Coffee             1045
Directions to Coffee             1034
Give me directions to Coffee     986
Directions to Coffee             875
Show me directions to Donut      812
Directions to Donut              789
.
.
.

我按照上一个问题的步骤来做,但最后一部分我被卡住了:

import re
import pandas as pd
sdf = pd.read_excel('C:\coffee_donut.xlsx')
rep = dict(zip(sdf.Token, sdf.Synonyms)) #convert into dictionary

rep = dict((re.escape(k), v) for k, v in rep.iteritems())
pattern = re.compile("|".join(rep.keys()))
rep = pattern.sub(lambda m: rep[re.escape(m.group(0))], **coffee_directions_df**)

print rep

如何将rep应用于数据帧??我很抱歉,如果这是一个愚蠢的问题。我真的很感谢你的帮助。你知道吗

谢谢!!你知道吗


Tags: to数据redfmecoffeegiverep
1条回答
网友
1楼 · 发布于 2024-04-29 03:23:02

你差点就成功了!下面是一个在当前代码中重用regex对象和lambda函数的解决方案。你知道吗

运行以下命令,而不是最后一行(rep = pattern.sub(...):

coffee_directions_df['Utterance'] = \
coffee_directions_df['Utterance'].str.replace(pattern, lambda m: rep[m.group(0)])

# Confirm replacement
coffee_directions_df
                          Utterance  Frequency
0          Directions to Coffee       1045
1          Directions to Coffee       1034
2  Give me directions to Coffee        986
3   Directions to Seattles Best        875
...

这是因为pd.Series.str.replace可以接受一个已编译的regex对象和一个函数;see the docs for more。你知道吗

相关问题 更多 >