0
$\begingroup$

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)
    ofile.write(s)

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

ifile.close()
ofile.close()
$\endgroup$
2
$\begingroup$

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)
$\endgroup$
2
  • $\begingroup$ Okay cool that would work, is there a way I import a csv or excel as the data? $\endgroup$ – Alex Kaczynski Jul 9 '18 at 12:39
  • $\begingroup$ yes, you can use pandas.read_csv() :) $\endgroup$ – pcko1 Jul 9 '18 at 12:41
0
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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