Packt+ | Advance your knowledge in tech (2024)

GO TO TOP

You're reading fromIPython Notebook Essentials

Product typeBook

Published inNov 2014

Publisher

ISBN-139781783988341

Pages190 pages

Edition1st Edition

Languages

Concepts

Scientific Computing

Author (1):

Packt+ | Advance your knowledge in tech (2)Luiz Felipe Martins

Luiz Felipe Martins

Luiz Felipe Martins holds a PhD in applied mathematics from Brown University and has worked as a researcher and educator for more than 20 years. His research is mainly in the field of applied probability. He has been involved in developing code for the open source homework system, WeBWorK, where he wrote a library for the visualization of systems of differential equations. He was supported by an NSF grant for this project. Currently, he is an Associate Professor in the Department of Mathematics at Cleveland State University, Cleveland, Ohio, where he has developed several courses in applied mathematics and scientific computing. His current duties include coordinating all first-year calculus sessions.

Read more

See other products by Luiz Felipe Martins

Table of Contents (15) Chapters

IPython Notebook Essentials

    Credits

      About the Author

        About the Reviewers

          www.PacktPub.com

            Preface

              1. A Tour of the IPython Notebook

              • Getting started with Anaconda or Wakari
              • Running the notebook
              • Example – the coffee cooling problem
              • Exercises
              • Summary

              2. The Notebook Interface

              • Editing and navigating a notebook
              • IPython magics
              • Interacting with the operating system
              • Running scripts, loading data, and saving data
              • The rich display system
              • Summary

              3. Graphics with matplotlib

              • The plot function
              • Three-dimensional plots
              • Animations
              • Summary

              4. Handling Data with pandas

              • The Series class
              • The DataFrame class
              • Computational and graphics tools
              • An example with a realistic dataset
              • Summary

              5. Advanced Computing with SciPy, Numba, and NumbaPro

              • Overview of SciPy
              • Advanced mathematical algorithms with SciPy
              • Accelerating computations with Numba and NumbaPro
              • Summary

              IPython Notebook Reference Card

              • Starting the notebook
              • Keyboard shortcuts
              • Importing modules
              • Getting help

              A Brief Review of Python

              • Introduction
              • Basic types, expressions, and variables and their assignment
              • Sequence types
              • Dictionaries
              • Control structures
              • Summary

              NumPy Arrays

              • Introduction
              • Array creation and member access
              • Indexing and Slicing

              Index

                Sequence types

                Python sequence types are used to represent ordered collections of objects. They are classified into mutable and immutable sequence types. Here, we will only discuss lists (mutable) and tuples and strings (both immutable). Other sequence types are mentioned at the end of this section.

                Lists

                The following example shows how to construct a list in Python and assign it to a variable:

                numbers = [0, 1.2, 234259399992, 4+3j]

                Individual entries in the list are accessed with index notation as follows:

                numbers[2]

                Notice that indexing always starts with 0. Negative indices are allowed and they represent positions starting at the end of the list. For example, numbers[-1] is the last entry, numbers[-2] is the next-to-last entry, and so forth.

                Since lists are a mutable sequence type, we are allowed to modify the entries in-place:

                numbers[0] = -3numbers[2] += numbers[0]print numbers

                Another important way to refer to elements in a Python sequence type is slices, which allow the extraction of sublists from a list. Since this topic is very important for NumPy arrays, we defer the discussion to Appendix C, NumPy Arrays.

                Python lists have a nice set of features, a few of which are illustrated in the following code examples:

                • To find the length of a list, use the following command:

                  len(numbers)
                • To reverse a list in place, use the following command:

                  numbers.reverse()print numbers
                • To append a new element, use the following command:

                  numbers.append(35)print numbers
                • To sort the list in-place, use the following command:

                  values = [1.2, 0.5, -3.4, 12.6, 3.5]values.sort()print valuesvalues.sort(reverse=True)print values
                • To insert a value at a position, use the following command:

                  values.insert(3, 6.8)print values
                • To extend a list, use the following command:

                  values.extend([7,8,9])print values

                Python has a few handy ways to construct frequently used lists. The range() function returns a list of equally spaced integers. The simplest form returns a list of successive integers starting at 0:

                range(10)

                The preceding command returns the following list:

                [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

                Note that the last element is one less than the argument given in the function call. The rule of thumb is that range(n) returns a list with n elements starting at zero so that the last element is n-1. To start at a nonzero value, use the two-argument version as follows:

                range(3, 17)

                A third argument specifies an increment. The following command line produces a list of all positive multiples of 6 that are less than 100:

                range(6,100,6)

                Negative increments can also be used:

                range(20, 2, -3)

                Lists support concatenation, which is represented by the + operator:

                l1 = range(1, 10)l2 = range(10, 0, -1)l3 = l1 + l2print l3

                Note

                Note that for the NumPy arrays, the + operator is redefined to represent vector/matrix addition.

                The multiplication operator (*) can be used to construct a list by repeating the elements of a given list, as follows:

                l4 = 3*[4,-1,5]print l4

                The most flexible way to construct a list in Python is to use a list comprehension. A full discussion is beyond the scope of this appendix, but the following examples illustrate some of the possibilities:

                • To display the list of the squares of the integers from 0 to 10 (inclusive), use the following command line:

                  [n ** 2 for n in range(11)]
                • To display the list of divisors of an integer, use the following command lines:

                  k = 60[d for d in range(1, k+1) if k % d == 0]
                • To display the list of prime numbers up to 100, use the following command line (very inefficient):

                  [k for k in range(2,101) if len([d for d in range(1, k+1) if k % d == 0])==2]
                • To display the list of tuples of points with integers coordinates and their distances to the origin, use the following command line:

                  [(i,j,(i*i+j*j)**0.5) for i in range(5) for j in range(6)]

                Tuples

                Tuples are similar to lists, but are immutable—once created, their elements cannot

                be changed. The following command lines will result in an error message:

                t1 = (2,3,5,7)t1[2] = -4

                Tuples have a few specialized uses in Python. They can be used as indexes in dictionaries (because they are immutable). They also consist of the mechanism that Python uses to return more than one value from a function. For example, the built-in function divmod() returns both the integer quotient and remainder in a tuple:

                divmod(213, 43)

                Tuples support the same sequence interface as lists, except for methods that would modify the tuple. For example, there is no method named sort() that sorts a tuple in place.

                Strings

                A Python string represents an immutable sequence of characters. There are two string types: str, representing ASCII strings, and unicode, representing Unicode strings.

                A string literal is a sequence of characters enclosed by either single quotes or double quotes, as follows:

                s1 = 'I am a string's2 = "I am a string"print s1print s2

                There is no semantic difference between single quotes and double quotes, except that a single-quoted string can contain double quotes and a double quoted string can contain single quotes. For example, the following command lines are correct:

                s3 = "I'm a string"print s3

                Strings are used for two main purposes: as dictionary indexes and to print messages. When printing messages, strings have the format() method that allows easy display of information. We use this feature frequently to add annotations to graphics. Here is an example:

                n = 3message = 'The square root of {:d} is approximately {:8.5f}.'.format(n, n ** 0.5)print message

                In the preceding example, there are two format specifiers:

                • {:d}: This specifies a decimal format for an integer value

                • {:8.5f}: This specifies a field of width 8 and 5 decimals for a floating-point value

                The format specifications are matched (in order) with the arguments, in this case n and n ** 0.5.

                Strings have a rich interface. If you need to code something with strings, it is very likely that there is a built-in function that does the job with very little modification. A list of all available string methods, as well as formatting features, is available at https://docs.python.org/2/library/stdtypes.html#string-methods.

                Packt+ | Advance your knowledge in tech (3)The rest of the chapter is locked

                Unlock this book and the full library FREE for 7 days

                Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of

                Renews at $15.99/month. Cancel anytime

                Start free trial

                Previous Section

                Section 4 of 7

                Next Section

                Packt+ | Advance your knowledge in tech (2024)
                Top Articles
                Latest Posts
                Article information

                Author: Dan Stracke

                Last Updated:

                Views: 5696

                Rating: 4.2 / 5 (43 voted)

                Reviews: 82% of readers found this page helpful

                Author information

                Name: Dan Stracke

                Birthday: 1992-08-25

                Address: 2253 Brown Springs, East Alla, OH 38634-0309

                Phone: +398735162064

                Job: Investor Government Associate

                Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

                Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.