From lists to unidimensional arrays

One of the most common situations you will encounter when working with data is transforming a list into an array.

When operating such a transformation, it is important to consider the objects the lists contain because this will determine the dimensionality and the dtype of the resulting array.

Let's start with this first example of a list containing just integers:

In: import numpy as np

In: # Transform a list into a uni-dimensional array
list_of_ints = [1,2,3]
Array_1 = np.array(list_of_ints)

In: Array_1

Out: array([1, 2, 3])

Remember that you can access a one-dimensional array as you would with a standard Python list (the indexing starts from zero):

In: Array_1[1] # let's output the second value

Out: 2

We can ask for further information about the type of the object and the type of its elements (the effectively resulting type depends on whether your system is 32-bit or 64-bit):

In: type(Array_1)

Out: numpy.ndarray

In: Array_1.dtype

Out: dtype('int64')
The default dtype depends on the system you're operating on.

Our simple list of integers will turn into a one-dimensional array; that is, a vector of 32-bit integers (ranging from -231 to 231-1, the default integer on the platform we used for our examples).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset