Skip to content

Instantly share code, notes, and snippets.

@psachin
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psachin/595197fc6c79dc5a1258 to your computer and use it in GitHub Desktop.
Save psachin/595197fc6c79dc5a1258 to your computer and use it in GitHub Desktop.
Import data as a Matrix and normalize its values by finding the mean of each column
#!/usr/bin/env python
import numpy as np
# Know the delimiter used(Useful to differentiate between a space and tab).
# f = open('test.txt')
# lines = f.readlines()
# print lines
# Uncomment below line to import data from a file.
# x = np.loadtxt('test.txt', delimiter="\t")
# print x
# print x.shape
# print x.shape[0]
# Test Matrix. Comment variable 'x' below if you are importing data from a file.
x = np.array([[1,2,3,4],
[3,4,2,1],
[3,4,6,1]])
# print x
# print "========="
# mean = np.mean(x[:,0])
# print mean
newlist = []
nl = []
# first row
for a in range(0, x.shape[1]):
mean = np.mean(x[:, a])
for i in range(0, x.shape[0]):
val = x[i, a] - mean
# print val
newlist.append(val)
# print x[i, a]
# print newlist
# print "------"
mean = np.mean(x[:, a])
nl.append(newlist)
newlist = []
print x
print " ------- Normalized values ---------"
# print nl
newarray = np.asarray(nl)
# Finally reverse the Matrix
print newarray.transpose()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment