954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

csv columns in python

How do you write a python code that looks at a specific cell in a csv file?
I have the following data in a csv file
1 0 100
2 11 150
3 0 189
4 0 195
5 21 245
I need to write a program in python that will count the number of non zero values in the SECOND column only. Any hints? All help is greatly appreciated.

machine91
Newbie Poster
5 posts since Jul 2011
Reputation Points: 10
Solved Threads: 0
 

Hello machine91!

Take a look at python's "csv" module. I believe it will give you what you need.

I'm a python noob, but here's a basic example that does something close to what I think you're looking for:

#!/usr/bin/python

import csv

csvInput = csv.reader(open('test.txt', 'rb'), delimiter=' ')
count = 0

for row in csvInput:
    print row[1],
    if row[1] != "0":
        print "non-zero!"
        count += 1
    else:
        print

print "Non-zero total: %s" % count


I hope this helps!
-G

Gromit
Posting Whiz in Training
212 posts since Sep 2008
Reputation Points: 47
Solved Threads: 31
 

Thank you for your help, you have certainly provided me with some ideas. Although the code I have now tried keeps giving me the error 'IndexError: list index out of range' Any ideas on what this error means and how I could solve it? Thanks again. :)

machine91
Newbie Poster
5 posts since Jul 2011
Reputation Points: 10
Solved Threads: 0
 

Interesting! One way I was able to reproduce that is with an extra line at the end of the input file. Here's a successful run:

-> cat -E test.txt 
1 0 100$
2 11 150$
3 0 189$
4 0 195$
5 21 245$

-> python test.py 
0
11 non-zero!
0
0
21 non-zero!
Non-zero total: 2


Here's a run with an extra line at the end of the csv file:

-> echo >> test.txt

-> cat -E test.txt 
1 0 100$
2 11 150$
3 0 189$
4 0 195$
5 21 245$
$

-> python test.py 
0
11 non-zero!
0
0
21 non-zero!
Traceback (most recent call last):
  File "test.py", line 9, in ?
    print row[1],
IndexError: list index out of range


So you might want to look at a way to check the input and trim out any blank lines, if there are any. It could also be something else entirely!...

Here's a simple example that checks to see if the list is empty before trying to process it:

#!/usr/bin/python
 
import csv
 
csvInput = csv.reader(open('test.txt', 'rb'), delimiter=' ')
count = 0
 
for row in csvInput:
    if row:
        print row[1],
        if row[1] != "0":
            print "non-zero!"
            count += 1
        else:
            print
 
print "Non-zero total: %s" % count


Again, I'm terrible at python, but I hope this helps! :)
-G

Gromit
Posting Whiz in Training
212 posts since Sep 2008
Reputation Points: 47
Solved Threads: 31
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: