Introduction To NUMPY
Introduction To NUMPY
CS158-1 -A23
2018138508 Introduction to NUMPY
Creating Arrays
URL: https://bookshelf.vitalsource.com/reader/books/9781119545675/epubcfi/
6/12[%3Bvnd.vst.idref%3DAc02]!/4/2/6/4[head-2-5]/1:19[rra%2Cys]
Page 20
Book Cover:
https://bookshelf.vitalsource.com/#/
Reshaping Arrays
Reshaping Arrays
You can reshape an array to another dimension using the reshape() function. Using the b5 (which
is a rank 1 array) example, you can reshape it to a rank 2 array as follows:
b5 = b5.reshape(1,-1)
print(b5)
'''
[[9 8 7 6 5]]
'''
In this example, you call the reshape() function with two arguments. The first 1 indicates that
you want to convert it into rank 2 array with 1 row, and the ‐1 indicates that you will leave it to
the reshape() function to create the correct number of columns. Of course, in this example, it is
clear that after reshaping there will be five columns, so you can call the reshape() function as
reshape(1,5). In more complex cases, however, it is always convenient to be able to use ‐1 to let
the function decide on the number of rows or columns to create.
b4.reshape(-1,)
'''
[9 8 7 6 5]
'''
The ‐1 indicates that you let the function decide how many rows to create as long as the end
result is a rank 1 array.
TIP:
To convert a rank 2 array to a rank 1 array, you can also use the flatten() or ravel() functions. The
flatten() function always returns a copy of the array, while the ravel() and reshape() functions
return a view (reference) of the original array.
URL: https://bookshelf.vitalsource.com/reader/books/9781119545675/epubcfi/
6/12[%3Bvnd.vst.idref%3DAc02]!/4/2/10/4[head-2-7]/1:14[rra%2Cys]
p. 26
Book Cover:
ITERATIONS OVERVIEW
Lesson 5 introduced control structures. These structures are used to “control” the flow of data
through an application. Python supports various structures through control statements of
sequence, iteration, and selection. In Lesson 5 selection and progression were discussed. The
sequence control structure (executed in a sequence statement) is completed one statement after
the other. The selection control structure (implemented in a selection statement) executes only
after a particular condition is met. Although these types of code statements allow applications to
run, in most cases, using only sequence and selection statements would make for very long
program code.
In this lesson, a third control structure is introduced: iteration. Iteration, along with iterative code
statements, provides efficiency in the program design and development of Python applications.
Further, in this lesson, iteration statements will be created using two specific types of iteration
structures (definite and indefinite loops) that each serve a distinct purpose.
Simply stated, iteration control structures, also known as loops, repeat actions. There are two
primary types of loops: loops that repeat actions a predetermined number of times (definite
loops) and loops that act until the algorithm determines that the execution of the loop should stop
(indefinite loops).
As you work through this lesson, there are a number of key terms you will see. These include the
following:
Sequence control structures are sequential line-by-line executions of program code within a
program.
Selection control structures allow programmers to ask questions, and then, based on the result,
perform different actions.
Iteration control structures allow programmers to execute code repeatedly. Examples of these
iteration structures are definite loops and indefinite loops.
URL:
https://bookshelf.vitalsource.com/reader/books/9781119817390/epubcfi/6/26[%3Bvnd.vst.idref
%3DAc07]!/4/2/6/6[c07-para-0003]/7:187[%20%5E(i%2Cmpl]
p.143
Book Cover:
https://bookshelf.vitalsource.com/reader/books/9781119817390/epubcfi/6/2[%3Bvnd.vst.idref
%3DAcover]!/4/2/2/4%4052:49
Join
In SQL we join tables based on a key, whereas in NumPy we join arrays by axes.
We pass a sequence of arrays that we want to join to the concatenate() function, along with the
axis. If axis is not explicitly passed, it is taken as 0.
The next thing we consider is how to join lists together. Luckily we have covered concatenation
earlier with strings and its very much the same for lists, lets demonstrate:
By using the addition symbol we can concatenate two or more lists together in the same way we
would a string.
URL: https://bookshelf.vitalsource.com/reader/books/9781119573289/epubcfi/
6/22[%3Bvnd.vst.idref%3DAc07]!/4/2/4/116/2
p33
Book Cover:
Split
STEP 5: SPLIT A TEXT VALUE
A complete street address includes (at least) two discrete values: the street name and the building
or house number. Remember that any text value is technically a string. While we humans see
words and phrases, Python (and most other programming languages) only sees a string of
individual characters rather than individual or meaningful words. We can use that to our
advantage if we want to reuse only part of a string value.
In this case, we can use the split function to split the full address string into individual parts,
using the space character as the defined separator in the string. We can then store each of those
individual values in a list and then use those values separately from the rest of the original string.
Update your code as shown in Listing 12.4.
LISTING 12.4
Splitting the address into pieces
# Name: Firstname Lastname
# Date created: Current date
# Purpose: Code-along for Python course
user_address = input("Enter an address (e.g., 123 Main Street): ")
if user_address.strip(): #check that string is not empty (after removing leading
#and trailing spaces)
print("Your address is " + user_address)
split_address = user_address.split()
When we run this code, Python will split the string into separate strings, using the space
character as the default separator. Those individual strings will be stored as separate values in a
list named split_address.
If you run the code at this point, you can't really see this happening. But you can include a
temporary print instruction to see the list itself, as shown in Listing 12.5.
LISTING 12.5
Displaying split information with a simple print
# Name: Firstname Lastname
# Date created: Current date
# Purpose: Code-along for Python course
LISTING 12.6
Commenting out unneeded code
# Name: Firstname Lastname
# Date created: Current date
# Purpose: Code-along for Python course
If you add temporary code to test the working code, you can certainly delete it when you are
done testing. However, commenting it out allows you to reuse the code if you need to later
without having to type it out. It also provides a certain level of documentation so that you can see
what you've already tested to avoid running the same tests multiple times. Note that we also
added a comment so that we could remember why we included the code in the first place.
URL: https://bookshelf.vitalsource.com/reader/books/9781119817390/epubcfi/
6/36[%3Bvnd.vst.idref%3DAc12]!/4/2/14/4[head-2-329]/1:24[VAL%2CUE]
Book Cover:
Search
Searching Strings
Python supports search operations on strings, using the in operator to check if a substring exists
in a string. This will perform an operation similar to searching a web page or other electronic
document for a specific word or phrase.
It is important to note that searches are case-sensitive by default, so a search for “He” is not the
same as a search for “he.” Normalizing the case means that the user can search for a string using
any case, regardless of the case that matching substrings are in.
As you will see in Listing 7.20, the in operator returns True if the first operand is contained
within the second, and False otherwise. In this situation, the output is Boolean: either the
substring exists in the message or it does not. The output does not tell us where the substring is
located inside the message, nor does it tell us how many times the substring appears in the
message.
LISTING 7.20
Searching within a string
message = "Hello, World!"
print("he" in message.lower())
print("ch" in message)
In this listing, we are again using the string “ Hello, World! ” We are also using the print function
to display the result of our checks. In the first check, using the in keyword, we are seeing if “ He
” is in the value contained within the message variable. “ He ” is in “ Hello, World! ” so the
result is True, which is displayed in the first line of the output:
True
False
True
False
The second check searches for “ he ” in the “ Hello, World! ” string stored in message. Because
the search is case-sensitive, “ he ” is not found and thus False is displayed. The third check
compares “ he ” to a lowercased version of the string in message, which would be True. Finally,
a check to see if “ ch ” is in our message string, which returns False because it is not.
URL:
https://bookshelf.vitalsource.com/reader/books/9781119817390/epubcfi/6/26[%3Bvnd.vst.idref
%3DAc07]!/4/2/16/28/12/4/4/4[c07-code-0050]/20
Book Cover:
Sort
SORTING LISTS
Python includes the sort method that allows us to sort the values of a list or to copy a list. By
default, the sort method will sort the values in a list alphabetically (for text values as shown in
Listing 8.27) or in ascending order (for numbers).
LISTING 8.27
Sort values in a list
names = ["Miriam","Mary","Dave","Nick"]
print(names)
names.sort()
print(names)
This script presents a simple list of names and then calls the sort() method on it. The result is a
list that includes the same names but in alphabetical order:
Filter
In the simple example in Listing 21.13, we want to find all names that start with “h” in the list.
LISTING 21.13
Using filter()
def initial_h(dataset):
for x in dataset:
if str.lower(x[0]) == "h": # normalize the case of the
# first letter and look for 'h'
return True
else:
return False
names=['Haythem','Mike','James','Helen','Mary']
print(names)
# extract the True results from the initial_h function to a new filter object
names_filtered = filter(initial_h,names)
print(type(names_filtered))
print(names_filtered_list)
We start by defining an initial_h function that looks at each item in a dataset and identifies the
values that start with “h.” We do this by checking the first position of each item after converting
it to lowercase. For each item checked in the dataset either True or False is returned.
We use the initial_h function in a filter on a names dataset to extract the names that return True in
the function to a new filter object, which we then convert to a list. The output from this listing
shows the initial list data, the type that was returned from the filter, the type of our converted
filter, and then the final output of running the filter:
['Haythem', 'Mike', 'James', 'Helen', 'Mary']
<class 'filter'>
<class 'list'>
['Haythem', 'Helen']
URL
p.475
https://bookshelf.vitalsource.com/reader/books/9781119817390/epubcfi/6/60[%3Bvnd.vst.idref
%3DAc21]!/4/2/14/18[c21-para-0055]/3:35[ang%2Ce%20r]
Book Cover: