Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Select Specific Row and Column

I wish to select a specific row and column from a CSV file in python. If the value is blank, I want to perform one action, and if the value is not blank, I want to perform another action.

I think the code should look something like this:

inputFile = 'example.csv'
reader = csv.reader(inputFile, 'rb')
for row in reader:
    if row[5][6] == '':              ==>  (I mean select value the 5th row and 6th column)
        (do this)
    else:
        (do that)

Any help or guidance on this topic would be helpful -- I've done a similar task using lists; however, since the CSV file is raw, I don't know what to do.

like image 968
Code4Days Avatar asked Dec 02 '22 19:12

Code4Days


2 Answers

When you think CSV, think pandas.

import pandas as pd

df = pd.read_csv('path/to/csv')

if df.iloc[5, 6]:
    # do stuff
else
    # do some other stuff
like image 58
bananafish Avatar answered Dec 06 '22 09:12

bananafish


Both inspectorG4dget and Oscar Lopez have the right idea, but there are flaws in their solutions. Thus, I present my own.

The general idea is that csv.reader is just a special file object that automatically splits things on commas. Treat it like any other file object. If you want the nth line, iterate until you hit the nth line.

with open('inputFile', rb) as f:
  reader = csv.reader(f)
  for i, l in enumerate(reader):
    if i==5:
      try:
        print l[6]
      except IndexError:
        print "Nothing here!"

A few notes:

  • I use a with block so that the file is safely closed on the completion of this code. You can always call file.close yourself, but this is better practice.
  • I wrap the access to the 6th column of the line in a try...except because, well, there might not be a 6th column. Better safe than sorry.
like image 35
whereswalden Avatar answered Dec 06 '22 10:12

whereswalden