Python Machine Learning Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

How to do it…

Let's see how to create an array in Python:

  1. To start off, import the NumPy library as follows:
>> import numpy as np

We just imported a necessary package, numpy. This is the fundamental package for scientific computing with Python. It contains, among other things, the following:

  • A powerful N-dimensional array object
  • Sophisticated broadcasting functions
  • Tools for integrating C, C++, and FORTRAN code
  • Useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious uses, NumPy is also used as an efficient multidimensional container of generic data. Arbitrary data types can be found. This enables NumPy to integrate with different types of databases.  

Remember, to import a library that is not present in the initial distribution of Python, you must use the pip install command followed by the name of the library. This command should be used only once and not every time you run the code.
  1. Let's create some sample data. Add the following line to the Python Terminal:
>> data = np.array([[3, -1.5, 2, -5.4], [0, 4, -0.3, 2.1], [1, 3.3, -1.9, -4.3]])

The np.array function creates a NumPy array. A NumPy array is a grid of values, all of the same type, indexed by a tuple of non-negative integers. rank and shape are essential features of a NumPy array. The rank variable is the number of dimensions of the array. The shape variable is a tuple of integers that returns the size of the array along each dimension.

  1. We display the newly created array with this snippet:
>> print(data)

The following result is returned:

[[ 3. -1.5  2.  -5.4]
[ 0. 4. -0.3 2.1]
[ 1. 3.3 -1.9 -4.3]]

We are now ready to operate on this data.