0% found this document useful (0 votes)
98 views15 pages

Introduction To NUMPY

The document discusses different ways to create NumPy arrays, including using functions like arange(), zeros(), full(), eye(), and random(). It also covers reshaping arrays using reshape() and flattening arrays using ravel() or flatten().

Uploaded by

Trisha Lao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views15 pages

Introduction To NUMPY

The document discusses different ways to create NumPy arrays, including using functions like arange(), zeros(), full(), eye(), and random(). It also covers reshaping arrays using reshape() and flattening arrays using ravel() or flatten().

Uploaded by

Trisha Lao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Lao, Trisha A.

CS158-1 -A23
2018138508 Introduction to NUMPY

 Creating Arrays

Creating NumPy Arrays


Before using NumPy, you first need to import the NumPy package (you may use its conventional
alias np if you prefer):
import numpy as np
The first way to make NumPy arrays is to create them intrinsically, using the functions built right
into NumPy. First, you can use the arange() function to create an evenly spaced array with a
given interval:
a1 = np.arange(10) # creates a range from 0 to 9
print(a1) # [0 1 2 3 4 5 6 7 8 9]
print(a1.shape) # (10,)
The preceding statement creates a rank 1 array (one‐dimensional) of ten elements. To get the
shape of the array, use the shape property. Think of a1 as a 10×1 matrix.
You can also specify a step in the arange() function. The following code snippet inserts a step
value of 2:
a2 = np.arange(0,10,2) # creates a range from 0 to 9, step 2
print(a2) # [0 2 4 6 8]
To create an array of a specific size filled with 0s, use the zeros() function:
a3 = np.zeros(5) # create an array with all 0s
print(a3) # [ 0. 0. 0. 0. 0.]
print(a3.shape) # (5,)
You can also create two‐dimensional arrays using the zeros() function:
a4 = np.zeros((2,3)) # array of rank 2 with all 0s; 2 rows and 3
# columns
print(a4.shape) # (2,3)
print(a4)
'''
[[ 0. 0. 0.]
[ 0. 0. 0.]]
'''
If you want an array filled with a specific number instead of 0, use the full() function:
a5 = np.full((2,3), 8) # array of rank 2 with all 8s
print(a5)
'''
[[8 8 8]
[8 8 8]]
'''
Sometimes, you need to create an array that mirrors an identity matrix. In NumPy, you can do so
using the eye() function:
a6 = np.eye(4) # 4x4 identity matrix
print(a6)
'''
[[ 1. 0. 0. 0.]
[ 0. 1. 0. 0.]
[ 0. 0. 1. 0.]
[ 0. 0. 0. 1.]]
'''
The eye() function returns a 2‐D array with ones on the diagonal and zeros elsewhere.
To create an array filled with random numbers, you can use the random() function from
the numpy.random module:
a7 = np.random.random((2,4)) # rank 2 array (2 rows 4 columns) with
# random values
# in the half-open interval [0.0, 1.0)
print(a7)
'''
[[ 0.48255806 0.23928884 0.99861279 0.4624779 ]
[ 0.18721584 0.71287041 0.84619432 0.65990083]]
'''
Another way to create a NumPy array is to create it from a Python list as follows:
list1 = [1,2,3,4,5] # list1 is a list in Python
r1 = np.array(list1) # rank 1 array
print(r1) # [1 2 3 4 5]
The array created in this example is a rank 1 array.

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.

Here is another example of how to reshape b4 (which is a rank 2 array) to rank 1:

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

Joining means putting contents of two or more arrays in a single array.

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

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()
print(split_address) # temporary instruction to verify the list
The output should look like:

Enter an address (e.g., 123 Main Street): 789 Bradford Street


Your address is 789 Bradford Street
['789', 'Bradford', 'Street']
We don't need this print statement in the full program, so we can comment it out after using it to
test the split function, as shown in Listing 12.6.

LISTING 12.6
Commenting out unneeded code
# 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()
#print(split_address) # temporary instruction to verify the list
NOTE Why Not Delete It?

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) # we use the in operator to check if the


# string "He" exists in "Hello World"

print("he" in message) #everything is case sensitive

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:

['Miriam', 'Mary', 'Dave', 'Nick']


['Dave', 'Mary', 'Miriam', 'Nick']
An important point here, though, is that this replaces the original list, so the order in which the
items originally appear is lost in the transformation.
p. 99
URL:
https://bookshelf.vitalsource.com/reader/books/9781119817390/epubcfi/6/28[%3Bvnd.vst.idref
%3DAc08]!/4/2/28/4[head-2-205]/1:11[LIS%2CTS]
Book Cover:

 Filter

USING THE FILTER() FUNCTION


The filter() function takes as input a condition that can be evaluated as True or False and an
iterable object, such as a list or dictionary. It applies the condition to each element in the object
and returns those elements that evaluate as True for the condition.

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))

# convert the filter object to a list object


names_filtered_list = list(names_filtered)
print(type(names_filtered_list))

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:

You might also like