I created a program that search and replaces over an entire csv file but I need to make so it is column specific. Is there a way to only search via a column. Here is my code, I am pretty new to python so I apologize if this is an easy fix.

import csv

ifile = open('testbook.csv', 'rb')
reader = csv.reader(ifile,delimiter='\t')
ofile = open('output.csv', 'wb')
writer = csv.writer(ofile, delimiter='\t')

findL = ['Australia', 'Mexico', 'United States', 'hob']
replaceL = ['Kangaroo', 'Spider Monkey', 'Eagle', 'Test']

rep = dict(zip(findL, replaceL))

def findReplace(find, replace):
    s = ifile.read()
    for item, replacement in zip(findL, replaceL):
        s = s.replace(item, replacement)

for item in findL:
    findReplace(item, rep[item])


2 Answers 2


You can do it easily by using pandas, like this:

import pandas as pd

data = [['Austria', 'Germany', 'hob', 'Australia'],
        ['Spain', 'France', 'Italy', 'Mexico']]

df = pd.DataFrame(data, columns = ['A','B','C','D'])

# Values to find and their replacements
findL = ['Australia', 'Mexico', 'United States', 'hob']
replaceL = ['Kangaroo', 'Spider Monkey', 'Eagle', 'Test']

# Select column (can be A,B,C,D)
col = 'C';

# Find and replace values in the selected column
df[col] = df[col].replace(findL, replaceL)
  • $\begingroup$ Okay cool that would work, is there a way I import a csv or excel as the data? $\endgroup$ Jul 9, 2018 at 12:39
  • $\begingroup$ yes, you can use pandas.read_csv() :) $\endgroup$
    – pcko1
    Jul 9, 2018 at 12:41

If you use OpenPyxl , you can use this line :

for col_cells in sheet.iter_cols(min_col=2, max_col=2):

Just enough to fix the number of rows or columns, you could fix one or both


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.