![](/img/trans.png)
[英]replacing columns values only on specific columns using regex in pandas
[英]Finding and replacing values in specific columns in a CSV file using dictionaries
我的目标是使用每个列的字典清理单个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
列housenum
,街道方向的stdir
等等,每个列都有其特定的拼写错误:
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)
并将此想法用于其他感兴趣的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.