使用字典查找和替换CSV文件中特定列中的值

2024-10-03 11:25:56 发布

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

我在这里的目标是使用字典为每个单独的列清理CSV文件中的地址数据。有点像自动化excel的查找和替换功能。地址分为列。^{{cd2>

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)

当代码正常工作时,我需要有单独的字典,因为有些列需要特定的输入错误修复。用于例如,Housenumbershousenumstdir表示街道方向等,每个列都有其特定于列的类型:

^{pr2}$

我不知道该怎么做,我觉得这很简单,或者我需要熊猫,但我不确定如何继续。谢谢你的帮助!还有没有什么方法可以把拼写错误和一个正确的错误组合在一起?我尝试了下面的方法,但是得到了一个不可修复的类型错误。在

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


Tags: csvtext字典here地址错误withopen
1条回答
网友
1楼 · 发布于 2024-10-03 11:25:56

你在找这样的东西吗?在

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)

把这个想法用在其他感兴趣的专栏上。在

相关问题 更多 >