NumPy (continued)
Key NumPy Functions
The following are functions from NumPy that we will be using a lot.
np.arange()
np.arange()
np.arange()
is a function that creates arrays of numerically order sets of numbers. It can take in either 1, 2 , or 3 arguments. When it uses 3 arguments, the first is the starting number that is included in your array, the second is the ending number which is not included in the array, and the third is how far apart the numbers in your array will be.
Let's go through some examples using 3 arguments.
The end argument in your range is not included, but the beginning value will be included. The end argument should always be one more than the number you want included in the array.
np.count_nonzero()
np.count_nonzero()
np.count_nonzero()
is a function that will count the number of True
values in an array.
All numbers except 0 are treated as True
values. 0 is considered a False
value.
You can insert numbers into the array or you can insert a boolean condition applied to an array. Here are some examples.
np.random.choice()
np.random.choice()
np.random.choice()
is a function that will randomly select items from an array.
When it selects from an array, it needs at least 1 argument. The argument is the array you want to select from. However, the common second argument is the number of items you want selected from your array. If the second argument is not specified, the function returns a single element by default. Having the second argument will convert the item or items selected into an array. Some examples of its functionality are shown below:
You can select from an array of strings, integers, or floats to name a few. It is not limited to strings.
Likewise, a possible third argument is replace = ...
. Replace is allows you to randomly select with or without replacement. In this case, you must either state replace = True
for with replacement or replace = False
for without replacement. If you draw with replacement it means you can have duplicates in your randomly selected array. If you draw without replacement, each item you select will be unique (only for that draw).
Here are some examples.
The general form of the function is as follows:
Computations / Array Arithmetic
A benefit that results from arrays having the same data type is that it allows us to apply addition, subtraction, multiplication, and division to entire arrays without fear. This can occur, because we will know whether we can use any of those computations just by looking at one item from our array since all items in the array have the same data type.
Here is an example of how we can change an array mathematically. The changes must be saved by defining a variable.
Summary
NumPy allows us to use arrays, which can be quicker and more efficient than lists.
Arrays are lists that hold only the same value types.
Remember that arrays are indexed starting at 0.
Last updated
Was this helpful?