Book Image

NumPy Beginner's Guide - Second Edition

By : Ivan Idris
Book Image

NumPy Beginner's Guide - Second Edition

By: Ivan Idris

Overview of this book

NumPy is an extension to, and the fundamental package for scientific computing with Python. In today's world of science and technology, it is all about speed and flexibility. When it comes to scientific computing, NumPy is on the top of the list. NumPy Beginner's Guide will teach you about NumPy, a leading scientific computing library. NumPy replaces a lot of the functionality of Matlab and Mathematica, but in contrast to those products, is free and open source. Write readable, efficient, and fast code, which is as close to the language of mathematics as is currently possible with the cutting edge open source NumPy software library. Learn all the ins and outs of NumPy that requires you to know basic Python only. Save thousands of dollars on expensive software, while keeping all the flexibility and power of your favourite programming language.You will learn about installing and using NumPy and related concepts. At the end of the book we will explore some related scientific computing projects. This book will give you a solid foundation in NumPy arrays and universal functions. Through examples, you will also learn about plotting with Matplotlib and the related SciPy project. NumPy Beginner's Guide will help you be productive with NumPy and have you writing clean and fast code in no time at all.
Table of Contents (19 chapters)
Numpy Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – creating universal function


We can create a universal function from a Python function with the NumPy frompyfunc function, as follows:

  1. Define a Python function that answers the ultimate question to the universe, existence, and the rest (it's from The Hitchhiker's Guide to the Galaxy; if you haven't read it, you can safely ignore this).

    def ultimate_answer(a):

    So far, nothing special; we gave the function the name ultimate_answer and defined one parameter, a.

  2. Create a result consisting of all zeros, that has the same shape as a, with the zeros_like function:

    result = np.zeros_like(a)
  3. Now set the elements of the initialized array to the answer 42 and return the result. The complete function should appear as shown, in the following code snippet. The flat attribute gives us access to a flat iterator that allows us to set the value of the array:

    def ultimate_answer(a):
       result = np.zeros_like(a)
       result.flat = 42
       return result
  4. Create a universal function with frompyfunc; specify...