首页 > 解决方案 > 使用字典查找和替换 CSV 文件中特定列中的值

问题描述

我的目标是使用每个列的字典从单个 CSV 文件中清理地址数据。有点像从 excel 中自动查找和替换功能。地址分为列。Housenumbers, streetnames,directionsstreettype所有在他们自己的列中。我使用以下代码来完成整个文档。

missad = {
'Typo goes here': 'Corrected typo goes here'}

def replace_all(text, dic):
for i, j in missad.items():
    text = text.replace(i, j)
return text

with open('original.csv','r') as csvfile:
text=csvfile.read()
text=replace_all(text,missad)

with open('cleanfile.csv','w') as cleancsv:
cleancsv.write(text)

虽然代码有效,但我需要有单独的字典,因为某些列需要特定的拼写错误修复。例如对于Housenumberscolumn housenumstdir对于 street direction 等等,每个列都有特定的拼写错误:

housenum = {
'One': '1',
'Two': '2
}
stdir = {
'NULL': ''}

我不知道如何继续,我觉得这很简单,或者我需要熊猫,但不确定如何继续。将不胜感激任何帮助!还有是否可以将错别字与一个更正的错别字组合在一起?我尝试了以下但得到了一个不可散列的类型错误。

missad = { ['Typo goes here',Typo 2 goes here',Typo 3 goes here']: 'Corrected typo goes here'}

标签: pythonexcel

解决方案


是这样的东西你在找什么?

import pandas as pd

df = pd.read_csv(filename, index_col=False)   #using pandas to read in the CSV file

#let's say in this dataframe you want to do corrections on the 'column for correction' column

correctiondict= {
                  'one': 1,
                  'two': 2
                 }

df['columnforcorrection']=df['columnforcorrection'].replace(correctiondict)

并将这个想法用于其他感兴趣的列。


推荐阅读