Thursday, July 14, 2011

Python for non programmers, part 2


Welcome back, grasshopper. Ready for another round?



Note:Before you begin, assumed you use Notepad++, go to Settings/Preferences and navigate to the "Language menu and tab settings" tab. Change the "Tab size" from 4 to 2, and make sure the "replace by space" option is selected.



Lesson 2: Simple data manipulation.



Today, we are going to take our original csv data file and add a couple of rows programatically. Our program will


  • Extend the table header (first row) with three new labels ("Sum", "Max", and "Description").

  • For each data row, compute the sum as a floating point number (like 3.0).

  • For each data row, compute the maximum as an integer point number (like 3).

  • For each data row, add a quick textual description that contains both numbers.




Open up a program file, e.g. csvcopy.py in your editor and create the following program (remember, leading whitespaces are important in python):


# Import libraries
import csv

# Open files and csv readers/writers
infile = open('data.txt', 'rb')
in_csv = csv.reader(infile, delimiter=',')
outfile = open('data2.txt', 'wb')
out_csv = csv.writer(outfile, delimiter=',')

# Go through the rows
is_header = True
for row in in_csv:
if is_header:
row = row + ['Sum', 'Max', 'Description']
is_header = False
else:
row.append(float(row[1]) + float(row[2]))
row.append(max(int(row[1]), int(row[2])))
row.append('Value pair of %s and %s' % (row[1], row[2]))
out_csv.writerow(row)




Just like last time, run the program and look at the output. It should look something like this:


Row A,Row B,Row C,Sum,Max,Description
Hello,1,2,3.0,2,Value pair of 1 and 2
World,3,4,7.0,4,Value pair of 3 and 4




Experiment with the program to do other data manipulation. Try to answer the following questions from looking at the file:


  • How do I access a single element in a list of values such as row

  • How do I create a comment?

  • How do I add two values?

  • How do I find the maximum of two values?

  • How do I create a floating point number from a text?

  • How do I create an integer number from a text?

  • How do I append a single value to a list (row)?

  • How do I append multiple values to a list (row) at once?



For bonus points, try to understand how the last row.append in the program works.
You can find more information about that here.

0 comments: