Showing posts with label using numpy arrays. Show all posts
Showing posts with label using numpy arrays. Show all posts

Friday, December 2, 2011

Some numpy notes

here are some numpy notes..
#create a numpy array

a = array([1,2,4])

#make this a column vector
a = a.reshape(len(a),1)

#append a new column vector to it
a = concatenate((a,a),axis=1)

#the append function is not working for me..so i will stick to concatenate

now let me give  a simple program to read a file of real numbers, compute the average of each row and write a new file with this columns of averages appended..
You need the scitools package and numpy installed to execute this

#program to read a file containing real numbers and sum the rows and take average. add the average as a new column and save
import sys
from numpy import *

try:
    infile = sys.argv[1]
    outfile = sys.argv[2]
except:
    print "lafda aiti tamma"

import scitools.filetable as ft
#x = []
#y = []
fin = open(infile, 'r')
fout = open(outfile, 'w')

#now read the x,y pairs from command line
#if len(sys.argv) % 2 != 0:
#    print "must enter even no of digits"
#    exit

#for i in range(2,len(sys.argv[2:])): #leave out the first two elements of sys.argv ie program name and output file
#    y.append(float(sys.argv[i])) if (i%2) else x.append(float(sys.argv[i]))

#x = array(x)
#y = array(y)

#read the table from the file and store as a matrix
table = ft.read(fin)

num_rows = table.shape[0]
num_columns = table.shape[1]
avg_col = []


for i in range(num_rows):
    avg_col.append(mean(table[i]))
      

avg_col = array(avg_col)
print table.shape
print avg_col.shape
avg_col = avg_col.reshape(len(avg_col),1)
table = concatenate((table,avg_col),axis=1)
ft.write(fout,table)