【问题标题】:Pandas replace with dictionary doesn't work for CSV filePandas 用字典替换不适用于 CSV 文件
【发布时间】:2021-08-08 20:00:25
【问题描述】:

我想用 csv 文件中单列中的完整单词替换缩写词。 csv 文件有 2 列(由管道符号分隔),有数千行,没有标题,如下所示:

c1109db0.wav|Was ist der Unterschied zwischen Gefahr und Risiko?
c112c091.wav|Die Gefahr wird z.B. in ein Risiko umgewandelt.
c11335c1.wav|Ein Sturz d.h. ein Fall von der Kante ist ein Risiko.

我创建了一个replacers 字典并希望将其作为df.replace() 的参数传递。

我尝试了几种在 Stackoverflow 上找到的方法,但在创建的新文件中仍然没有替换缩写词。

我的代码:

import pandas as pd

def write_out_abbreviations():
    """Replace abbreviations in metadata file with full words."""
    # Read file into dataframe.
    with open('/home/username/data/metadata.csv') as f:
        df = pd.read_csv(f, names=['Audio_Filename', 'Segment_Text'], sep='|')
        # Create dictionary that contains abbreviations and their full words.
        replacers = {
            'bspw.': 'beispielsweise',
            'bzw.': 'beziehungsweise',
            ' ca.': ' zirka',
            'd.h.': 'das heißt',
            'Dr.': 'Doktor',
            ' ggf.': ' gegebenenfalls',
            'i.d.R.': 'in der Regel',
            ' inkl.': ' inklusive',
            'insb.': 'insbesondere',
            'Tel.': 'Telefon',
            'z.B.': 'zum Beispiel'}

        # Replace abbreviations in 'Segment_Text' column.

        # APPROACH 1:
        # df2 = df.replace({'Segment_Text': {replacers}})

        # APPROACH 2:
        # df2 = df['Segment_Text'].replace(replacers)

        # APPROACH 3:
        # df2 = df.Segment_Text.str.split()
        # df2 = df.Segment_Text.apply(lambda x: ' '.join([replacers.get(e, e) for e in x]))

        # APPROACH 4:
        # df['Segment_Text'] = df['Segment_Text'].map(replacers).fillna(df['Segment_Text'])

        # Write this dataframe to new file.
        d2f.to_csv('/home/username/data/metadata_REPLACED.csv',  # or df.to_csv...
                   header=False, index=False, sep='|')

write_out_abbreviations()

谁能告诉我我做错了什么?

感谢任何提示和技巧。谢谢!

【问题讨论】:

  • 请考虑下次提供英文样本输入,SO是英文网站。

标签: python pandas dictionary replace


【解决方案1】:

您正在使用正则表达式和替换函数查找Series.str.replace function

rx = re.compile('|'.join(replacers.keys()))
df2 = df['Segment_Text'].str.replace(rx, lambda m: replacers[m.group(0)])

它给df2

0    Was ist der Unterschied zwischen Gefahr und Ri...
1    Die Gefahr wird zum Beispiel in ein Risiko umg...
2    Ein Sturz das heißt ein Fall von der Kante ist...
Name: Segment_Text, dtype: object

【讨论】:

    【解决方案2】:

    你可以试试这个:

    示例输入:

    import pandas as pd
    df = pd.DataFrame({'c1109db0.wav': {0: 'c112c091.wav', 1: 'c11335c1.wav'},
     'Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?': {0: 'Die Gefahr wird z.B. in ein Risiko umgewandelt.',
      1: 'Ein Sturz d.h. ein Fall von der Kante ist ein Risiko.'}})
    

    代码:

    replacers = {
        'bspw.': 'beispielsweise',
        'bzw.': 'beziehungsweise',
        'ca.': ' zirka',
        'd.h.': 'das heißt',
        'Dr.': 'Doktor',
        'ggf.': ' gegebenenfalls',
        'i.d.R.': 'in der Regel',
        'inkl.': ' inklusive',
        'insb.': 'insbesondere',
        'Tel.': 'Telefon',
        'z.B.': 'zum Beispiel'}
    
    df.iloc[:,1] = df.iloc[:,1].str.split().map(lambda lst: ' '.join([replacers.get(word, word) for word in lst]))
    
    # Out[158]:
    # 0    Die Gefahr wird zum Beispiel in ein Risiko umg...
    # 1    Ein Sturz das heißt ein Fall von der Kante ist...
    # Name: Was_ist_der_Unterschied_zwischen_Gefahr_und_Risiko?, dtype: object
    

    顺便说一句。我不会在缩写中包含空格。而是将空格上的整个句子分成一串单词。然后将列表中的每个单词提供给字典,如果没有匹配,则使用默认值。

    【讨论】:

    • 嗯,不幸的是,它仍然对我不起作用。我不知道为什么不,也许错误出在其他地方。新文件已创建,没有错误,但缩写仍然存在。
    • 你必须设置df.iloc[:,1] = df.iloc[..... 我调整了我的答案以使其更清晰。
    • 啊当然! 掌心 感谢您指出这一点!现在它可以工作了:-)
    猜你喜欢
    • 1970-01-01
    • 2017-08-21
    • 2019-05-07
    • 2022-01-13
    • 2020-10-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    相关资源
    最近更新 更多