Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

columns in csv to python

Status
Not open for further replies.

machine91

Programmer
Jul 6, 2011
1
GB
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.
 
It would be something like this:
Code:
[COLOR=#a020f0]import[/color] string

data_file = "[COLOR=#ff00ff]my_data.dat[/color]"

all_count=0
nozero_count = 0
[COLOR=#0000ff]# read file line by line using the iterator open() or file()[/color]
[COLOR=#0000ff]#for line in open(data_file):[/color]
[COLOR=#804040][b]for[/b][/color] line [COLOR=#804040][b]in[/b][/color] file(data_file):
  [COLOR=#0000ff]# original line[/color]
  [COLOR=#804040][b]print[/b][/color] "[COLOR=#ff00ff]original line = '%s'[/color]" % line[:-1]
  [COLOR=#0000ff]# split line into list[/color]
  line_list = line.split()
  [COLOR=#0000ff]# numeric value (integer) of the second element[/color]
  my_int = string.atoi(line_list[1])
  [COLOR=#804040][b]print[/b][/color] "[COLOR=#ff00ff]2.number = %d[/color]" % my_int
  [COLOR=#804040][b]if[/b][/color] my_int != 0:
    nozero_count += 1
  all_count += 1
[COLOR=#804040][b]print[/b][/color] "[COLOR=#ff00ff]second column has %d non zero elements of all %d.[/color]"[COLOR=#6a5acd]\[/color]
  % (nozero_count, all_count)
Result (with Python 2.5.1):
Code:
> python process_datafile.py
original line = '1 0 100'
2.number = 0
original line = '2 11 150'
2.number = 11
original line = '3 0 189'
2.number = 0
original line = '4 0 195'
2.number = 0
original line = '5 21 245'
2.number = 21
second column has 2 non zero elements of all 5.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top