Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – working with NumPy arrays


Let's explore some ways to select elements and sub-arrays from NumPy arrays:

import numpy

a = numpy.arange(9.0)
print("Array a:")
print(a)

a = a.reshape((3,3))
print("Array a, reshaped:")
print(a)

print("Selecting an element: {0}".format(a[1,0]))
print("Selecting a row: {0}".format(a[1]))

print("Selecting a submatrix:")
print(a[1:3,1:3])

b = numpy.arange(9.0, 0.0, -1.0)
print("\nArray b: {0}".format(b))
indices, = numpy.where(b > 4.0)
print("Indices of elements of b > 4.0: {0}".format(indices))
print("b > 4.0: {0}".format(b[b > 4.0]))

The output should be as follows:

What just happened?

We used the arange function to create an array with nine floating-point elements. Since we only provided a single argument, NumPy assumes that the first element is zero and the increment is one. We then used the array's reshape method to return a two-dimensional array with three rows and three columns. reshape accepts a tuple that contains the dimensions...