6. Simple array operations

Simple array operations

Those of you who use (have used) Origin are you used to doing simple manipulation of datasets with the embedded spreadsheet functionality. Selecting data, only using every nth datapoint etc. are capabilities that we need all the time. This short tutorial will introduce a few array manipulations in Python. A more substantial introduction can be found at the numpy tutorial page. There are also two excellent video tutorials that I highly recommend watching on array indexing by Enthought can be viewed here and here.

First, let’s create a couple of datasets.
import numpy
1-d data:
one_d = numpy.linspace(0,100,100)
2-d data:
two_d = numpy.zeros((len(one_d),2))
two_d[:,0] = one_d
two_d[:,1] = one_d**3 + 14.5*2

Selecting points from 5th row onwards in 1-d array. Remember, Python indexes from 0.
new_array = one_d[4:]

Selecting points from 5th row onwards in 2-d array.
new_array = two_d[4:,:]

Selecting every 2nd point in the 1-d array.
new_array = one_d[::2]

Selecting every 2nd point in the 2-d array.
new_array = two_d[::2,:]

Remove the last 5 points from the 1-d array.
new_array = one_d[:-5]

Sorting is usually trivial in numpy with the sort command.
one_d.sort()

Sort y according to x in the 2-d array.
indices = numpy.argsort(two_d[:,0])
x = two_d[:,0]
new_x = x[indices]

y = two_d[:,1]
new_y = y[indices]

two_d[:,0] = new_x
two_d[:,1] = new_y

Selecting x values such that (20 < x <67) and the corresponding y values.
x = two_d[:,0]
y = two_d[:,1]

index = (x>20) & (x<67)
new_x = x[index]
new_y = y[index]

That’s all for now, folks! Drop me a line via the suggestion box or email MESA (mesa@mesa.ac.nz)  if you have any questions or requests.

Post contributed by Shrividya Ravi, VUW

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>