Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Operating with Arrays using NumPy | Python Basics
Introduction to Finance with Python
course content

Зміст курсу

Introduction to Finance with Python

Introduction to Finance with Python

1. Python Basics
2. Options Trading
3. Time Series Forecasting

Operating with Arrays using NumPy

Introduction

Now we are going to discover a library, which will be useful for more advanced usage of arrays, by providing a special data structure, called ndarray - NumPy.

To import this library standard code is import numpy as np.

Creating arrays

Let's assume that we have a standard list variable lst. If we are going to create a one dimensional NumPy array called arr, which will correspond to this variable, we should use the next code:

1234567
import numpy as np # Creating list of integers called `lst` lst = [1, 2, 3] # Creating NumPy array `arr` from list `lst` arr = np.array(lst) print(arr) print(type(arr))
copy

Now, if we want to create a new two dimensional array called arr, we have to pass as argument to np.array list of arrays/lists of the same length. For example:

1234
import numpy as np # Creating array, in which the first row is [0, 1] and the second is [2, 3] arr = np.array([[0, 1], [2, 3]]) print(arr)
copy

We also should notice such a fact, that in NumPy all elements/lists of elements should be of the same type (for example, all elements should be int, or all elements should be float, or all elements should be list of int, etc.)

Aggregation methods

Unlike ordinary lists, NumPy arrays also provide a set of aggregation methods. For example, the code below shows how to get minimum value from one-dimensional array a:

123456
import numpy as np # Initializing array `a` a = np.array([0, 1, 2, 3, -1]) # Getting minimum value from `a` min_ = a.min() print(min_)
copy

In case when we work with a multidimensional array, we should directly specify the axis, along which corresponding aggregation function will be taken. It could be done by setting the necessary value to the parameter axis of the corresponding method.

For example, in case of two-dimensional array a, taking mean value for each column could be performed using next code:

123456
import numpy as np # Initializing array `a` a = np.array([[1, 2, 3, 0], [4, 5, 6, 9]]) # Getting mean value for each column of `a` mean_ = a.mean(axis = 0) print(mean_)
copy

Additional concepts

In order to see explanations and examples of some more advanced concepts - watch the video below:

What are the valid expressions for merging arrays a = np.array([[1, 2], [3, 4], [5, 6]]) and b = np.array([7, 8])(several variants may be right)?

Виберіть кілька правильних відповідей

Все було зрозуміло?

Секція 1. Розділ 4
We're sorry to hear that something went wrong. What happened?
some-alt