There is a library of data science tools called Numpy that you will use all the time in your Python programs. In this library, is a special object called an array. You can think of an array object as very similar to a list.
Here is what it looks like to create an array object and give it a name (store it in a variable):
import numpy as np nums = np.array([1, 2, 3, 4, 5]) moreNums = np.array(1.1, 2.2, 3.3, 4.4)
Please notice that you need to import the NumPy library to use the array object in your program. You can do this by writing the statement
import numpy as np at the top of your program.
Secondly, the statement
np.array() is following a very important concept in object oriented programming called dot notation. Dot notation is how we access attributes and call methods. The statement
np.array() is calling the method
array of the
np object. The
array method creates a new array object.
Hopefully dot notation looks familiar to you; you have already been using dot notation in some of our programs that contain dictionaries, which are also objects in Python! Does
dictionary.keys() look familiar? This statement is calling the method
keys() of a dictionary object.
An array object has specific attributes that enable you to discover information about its structure and contents. When you want to gain access to the attribute of a given object, you still use dot notation, like so:
Need to call a method on an object? Follow this pattern instead:
Here is what it looks like to access the
dtype attribute that all array objects have:
nums refers to the variable that is storing our array object from the first code segment seen above. The name
dtype refers to the variable that all array objects have to describe the type of values that can be found in them. In the case of
nums, the value stored in the
dtype attribute would be
int64 because integers are stored within the array. For performance reasons, NumPy is written in the C programming language and uses C’s data types. By default, NumPy stores integers as the NumPy type int64 values — which correspond to 64-bit (8-byte) integers in C — and stores floating-point numbers as the NumPy type float64 values — which correspond to 64-bit (8-byte) floating-point values in C. In our examples, most commonly you’ll see the types int64, float64, bool (for Boolean) and object for non-numeric data (such as strings).
Size of Array ObjectsYou can view an array’s total number of elements with the attribute `size`: