python - 使用字典查找和替换 CSV 文件中特定列中的值
问题描述
我的目标是使用每个列的字典从单个 CSV 文件中清理地址数据。有点像从 excel 中自动查找和替换功能。地址分为列。Housenumbers
, streetnames
,directions
和streettype
所有在他们自己的列中。我使用以下代码来完成整个文档。
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)
虽然代码有效,但我需要有单独的字典,因为某些列需要特定的拼写错误修复。例如对于Housenumbers
column housenum
,stdir
对于 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'}
解决方案
是这样的东西你在找什么?
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)
并将这个想法用于其他感兴趣的列。
推荐阅读
- python - 熊猫合并不等于
- angular - 如何在 Angular 中实现 api 测试
- python - 在 python 的 y 轴上添加额外的标签 - 120%?
- kubernetes - 通过在种子列表中添加服务条目形成 cassandra 集群
- apache-spark-sql - 如果有连接,则连接两个数据集并从第二个表中选择列
- java - 有什么方法可以删除链表中的重复项我是否尝试过一种方法,但它给了我索引超出范围的异常?
- angular - 不更新自定义下拉列表中的 selectedItem
- macos-catalina - 是否可以在 macOS Catalina 上运行 GridLab-D?
- python-3.x - 如何获取文件创建时间戳作为 isodate
- excel - 如何在 VBA 中的 RegEX 之后删除特定数量的字符串?