导入txt文件与脚本字典和将其应用于数据框代替字词(importing txt file with

2019-09-28 05:57发布

我想使用一个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 ,我要用来导入和替换某些字符串(类似于由熊猫数据框中检查更换的话问)。

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

我该如何申请的代表到数据帧? 我很抱歉,如果这是这样一个noob问题。 我真的很感谢你的帮助。

谢谢!!

Answer 1:

你几乎拥有了! 下面是重新使用在当前的代码中的正则表达式对象和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可以接受编译正则表达式对象和功能; 看到文档的更多 。



文章来源: importing txt file with dictionary script and applying it to dataframe to replace words