ECOSYSTEM
Nearly every scientist working in Python draws on the power of NumPy.
NumPy brings the computational power of languages like C and Fortran to Python, a language much easier to learn and use. With this power comes simplicity: a solution in NumPy is often clear and elegant.
NumPy’s API is the starting point when libraries are written to exploit innovative hardware, create specialized array types, or add capabilities beyond what NumPy provides.

- Extract, Transform, Load:Pandas, Intake, PyJanitor
- Exploratory analysis:Jupyter, Seaborn, Matplotlib, Altair
- Model and evaluate:scikit-learn, statsmodels, PyMC3, spaCy
- Report in a dashboard:Dash, Panel, Voila
For high data volumes, Dask and Ray are designed to scale. Stable deployments rely on data versioning (DVC), experiment tracking (MLFlow), and workflow automation (Airflow, Dagster and Prefect).

NumPy forms the basis of powerful machine learning libraries like scikit-learn and SciPy. As machine learning grows, so does the list of libraries built on NumPy. TensorFlow’s deep learning capabilities have broad applications — among them speech and image recognition, text-based applications, time-series analysis, and video detection. PyTorch, another deep learning library, is popular among researchers in computer vision and natural language processing. MXNet is another AI package, providing blueprints and templates for deep learning.
Statistical techniques called ensemble methods such as binning, bagging, stacking, and boosting are among the ML algorithms implemented by tools such as XGBoost, LightGBM, and CatBoost — one of the fastest inference engines. Yellowbrick and Eli5 offer machine learning visualizations.








NumPy is an essential component in the burgeoning Python visualization landscape, which includes Matplotlib, Seaborn, Plotly, Altair, Bokeh, Holoviz, Vispy, Napari, and PyVista, to name a few.
NumPy’s accelerated processing of large arrays allows researchers to visualize datasets far larger than native Python could handle.
NumPy: the absolute basics for beginners#
Welcome to the absolute beginner’s guide to NumPy! If you have comments or suggestions, please don’t hesitate to reach out!
Welcome to NumPy!#
NumPy (Numerical Python) is an open source Python library that’s used in almost every field of science and engineering. It’s the universal standard for working with numerical data in Python, and it’s at the core of the scientific Python and PyData ecosystems. NumPy users include everyone from beginning coders to experienced researchers doing state-of-the-art scientific and industrial research and development. The NumPy API is used extensively in Pandas, SciPy, Matplotlib, scikit-learn, scikit-image and most other data science and scientific Python packages.
The NumPy library contains multidimensional array and matrix data structures (you’ll find more information about this in later sections). It provides ndarray, a homogeneous n-dimensional array object, with methods to efficiently operate on it. NumPy can be used to perform a wide variety of mathematical operations on arrays. It adds powerful data structures to Python that guarantee efficient calculations with arrays and matrices and it supplies an enormous library of high-level mathematical functions that operate on these arrays and matrices.
Learn more about NumPy here !
Installing NumPy#
To install NumPy, we strongly recommend using a scientific Python distribution. If you’re looking for the full instructions for installing NumPy on your operating system, see Installing NumPy.
If you already have Python, you can install NumPy with:
If you don’t have Python yet, you might want to consider using Anaconda. It’s the easiest way to get started. The good thing about getting this distribution is the fact that you don’t need to worry too much about separately installing NumPy or any of the major packages that you’ll be using for your data analyses, like pandas, Scikit-Learn, etc.
How to import NumPy#
To access NumPy and its functions import it in your Python code like this:
We shorten the imported name to np for better readability of code using NumPy. This is a widely adopted convention that you should follow so that anyone working with your code can easily understand it.
Reading the example code#
If you aren’t already comfortable with reading tutorials that contain a lot of code, you might not know how to interpret a code block that looks like this:
If you aren’t familiar with this style, it’s very easy to understand. If you see >>> , you’re looking at input, or the code that you would enter. Everything that doesn’t have >>> in front of it is output, or the results of running your code. This is the style you see when you run python on the command line, but if you’re using IPython, you might see a different style. Note that it is not part of the code and will cause an error if typed or pasted into the Python shell. It can be safely typed or pasted into the IPython shell; the >>> is ignored.
What’s the difference between a Python list and a NumPy array?#
NumPy gives you an enormous range of fast and efficient ways of creating arrays and manipulating numerical data inside them. While a Python list can contain different data types within a single list, all of the elements in a NumPy array should be homogeneous. The mathematical operations that are meant to be performed on arrays would be extremely inefficient if the arrays weren’t homogeneous.
Why use NumPy?
NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types. This allows the code to be optimized even further.
What is an array?#
An array is a central data structure of the NumPy library. An array is a grid of values and it contains information about the raw data, how to locate an element, and how to interpret an element. It has a grid of elements that can be indexed in various ways . The elements are all of the same type, referred to as the array dtype .
An array can be indexed by a tuple of nonnegative integers, by booleans, by another array, or by integers. The rank of the array is the number of dimensions. The shape of the array is a tuple of integers giving the size of the array along each dimension.
One way we can initialize NumPy arrays is from Python lists, using nested lists for two- or higher-dimensional data.
We can access the elements in the array using square brackets. When you’re accessing elements, remember that indexing in NumPy starts at 0. That means that if you want to access the first element in your array, you’ll be accessing element “0”.
More information about arrays#
This section covers 1D array , 2D array , ndarray , vector , matrix
You might occasionally hear an array referred to as a “ndarray,” which is shorthand for “N-dimensional array.” An N-dimensional array is simply an array with any number of dimensions. You might also hear 1-D, or one-dimensional array, 2-D, or two-dimensional array, and so on. The NumPy ndarray class is used to represent both matrices and vectors. A vector is an array with a single dimension (there’s no difference between row and column vectors), while a matrix refers to an array with two dimensions. For 3-D or higher dimensional arrays, the term tensor is also commonly used.
What are the attributes of an array?
An array is usually a fixed-size container of items of the same type and size. The number of dimensions and items in an array is defined by its shape. The shape of an array is a tuple of non-negative integers that specify the sizes of each dimension.
In NumPy, dimensions are called axes. This means that if you have a 2D array that looks like this:
Your array has 2 axes. The first axis has a length of 2 and the second axis has a length of 3.
Just like in other Python container objects, the contents of an array can be accessed and modified by indexing or slicing the array. Unlike the typical container objects, different arrays can share the same data, so changes made on one array might be visible in another.
Array attributes reflect information intrinsic to the array itself. If you need to get, or even set, properties of an array without creating a new array, you can often access an array through its attributes.
How to create a basic array#
This section covers np.array() , np.zeros() , np.ones() , np.empty() , np.arange() , np.linspace() , dtype
To create a NumPy array, you can use the function np.array() .
All you need to do to create a simple array is pass a list to it. If you choose to, you can also specify the type of data in your list. You can find more information about data types here .
You can visualize your array this way:

Be aware that these visualizations are meant to simplify ideas and give you a basic understanding of NumPy concepts and mechanics. Arrays and array operations are much more complicated than are captured here!
Besides creating an array from a sequence of elements, you can easily create an array filled with 0 ’s:
Or an array filled with 1 ’s:
Or even an empty array! The function empty creates an array whose initial content is random and depends on the state of the memory. The reason to use empty over zeros (or something similar) is speed — just make sure to fill every element afterwards!
You can create an array with a range of elements:
And even an array that contains a range of evenly spaced intervals. To do this, you will specify the first number, last number, and the step size.
You can also use np.linspace() to create an array with values that are spaced linearly in a specified interval:
Specifying your data type
While the default data type is floating point ( np.float64 ), you can explicitly specify which data type you want using the dtype keyword.
Adding, removing, and sorting elements#
This section covers np.sort() , np.concatenate()
Sorting an element is simple with np.sort() . You can specify the axis, kind, and order when you call the function.
If you start with this array:
You can quickly sort the numbers in ascending order with:
In addition to sort, which returns a sorted copy of an array, you can use:
argsort , which is an indirect sort along a specified axis,
lexsort , which is an indirect stable sort on multiple keys,
searchsorted , which will find elements in a sorted array, and
partition , which is a partial sort.
To read more about sorting an array, see: sort .
If you start with these arrays:
You can concatenate them with np.concatenate() .
Or, if you start with these arrays:
You can concatenate them with:
In order to remove elements from an array, it’s simple to use indexing to select the elements that you want to keep.
To read more about concatenate, see: concatenate .
How do you know the shape and size of an array?#
This section covers ndarray.ndim , ndarray.size , ndarray.shape
ndarray.ndim will tell you the number of axes, or dimensions, of the array.
ndarray.size will tell you the total number of elements of the array. This is the product of the elements of the array’s shape.
ndarray.shape will display a tuple of integers that indicate the number of elements stored along each dimension of the array. If, for example, you have a 2-D array with 2 rows and 3 columns, the shape of your array is (2, 3) .
For example, if you create this array:
To find the number of dimensions of the array, run:
To find the total number of elements in the array, run:
And to find the shape of your array, run:
Can you reshape an array?#
This section covers arr.reshape()
Yes!
Using arr.reshape() will give a new shape to an array without changing the data. Just remember that when you use the reshape method, the array you want to produce needs to have the same number of elements as the original array. If you start with an array with 12 elements, you’ll need to make sure that your new array also has a total of 12 elements.
If you start with this array:
You can use reshape() to reshape your array. For example, you can reshape this array to an array with three rows and two columns:
With np.reshape , you can specify a few optional parameters:
a is the array to be reshaped.
newshape is the new shape you want. You can specify an integer or a tuple of integers. If you specify an integer, the result will be an array of that length. The shape should be compatible with the original shape.
order: C means to read/write the elements using C-like index order, F means to read/write the elements using Fortran-like index order, A means to read/write the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. (This is an optional parameter and doesn’t need to be specified.)
If you want to learn more about C and Fortran order, you can read more about the internal organization of NumPy arrays here . Essentially, C and Fortran orders have to do with how indices correspond to the order the array is stored in memory. In Fortran, when moving through the elements of a two-dimensional array as it is stored in memory, the first index is the most rapidly varying index. As the first index moves to the next row as it changes, the matrix is stored one column at a time. This is why Fortran is thought of as a Column-major language. In C on the other hand, the last index changes the most rapidly. The matrix is stored by rows, making it a Row-major language. What you do for C or Fortran depends on whether it’s more important to preserve the indexing convention or not reorder the data.
How to convert a 1D array into a 2D array (how to add a new axis to an array)#
This section covers np.newaxis , np.expand_dims
You can use np.newaxis and np.expand_dims to increase the dimensions of your existing array.
Using np.newaxis will increase the dimensions of your array by one dimension when used once. This means that a 1D array will become a 2D array, a 2D array will become a 3D array, and so on.
For example, if you start with this array:
You can use np.newaxis to add a new axis:
You can explicitly convert a 1D array with either a row vector or a column vector using np.newaxis . For example, you can convert a 1D array to a row vector by inserting an axis along the first dimension:
Or, for a column vector, you can insert an axis along the second dimension:
You can also expand an array by inserting a new axis at a specified position with np.expand_dims .
For example, if you start with this array:
You can use np.expand_dims to add an axis at index position 1 with:
You can add an axis at index position 0 with:
Find more information about newaxis here and expand_dims at expand_dims .
Indexing and slicing#
You can index and slice NumPy arrays in the same ways you can slice Python lists.
You can visualize it this way:

You may want to take a section of your array or specific array elements to use in further analysis or additional operations. To do that, you’ll need to subset, slice, and/or index your arrays.
If you want to select values from your array that fulfill certain conditions, it’s straightforward with NumPy.
For example, if you start with this array:
You can easily print all of the values in the array that are less than 5.
You can also select, for example, numbers that are equal to or greater than 5, and use that condition to index an array.
You can select elements that are divisible by 2:
Or you can select elements that satisfy two conditions using the & and | operators:
You can also make use of the logical operators & and | in order to return boolean values that specify whether or not the values in an array fulfill a certain condition. This can be useful with arrays that contain names or other categorical values.
You can also use np.nonzero() to select elements or indices from an array.
Starting with this array:
You can use np.nonzero() to print the indices of elements that are, for example, less than 5:
In this example, a tuple of arrays was returned: one for each dimension. The first array represents the row indices where these values are found, and the second array represents the column indices where the values are found.
If you want to generate a list of coordinates where the elements exist, you can zip the arrays, iterate over the list of coordinates, and print them. For example:
You can also use np.nonzero() to print the elements in an array that are less than 5 with:
If the element you’re looking for doesn’t exist in the array, then the returned array of indices will be empty. For example:
Read more about using the nonzero function at: nonzero .
How to create an array from existing data#
This section covers slicing and indexing , np.vstack() , np.hstack() , np.hsplit() , .view() , copy()
You can easily create a new array from a section of an existing array.
Let’s say you have this array:
You can create a new array from a section of your array any time by specifying where you want to slice your array.
Here, you grabbed a section of your array from index position 3 through index position 8.
You can also stack two existing arrays, both vertically and horizontally. Let’s say you have two arrays, a1 and a2 :
You can stack them vertically with vstack :
Or stack them horizontally with hstack :
You can split an array into several smaller arrays using hsplit . You can specify either the number of equally shaped arrays to return or the columns after which the division should occur.
Let’s say you have this array:
If you wanted to split this array into three equally shaped arrays, you would run:
If you wanted to split your array after the third and fourth column, you’d run:
You can use the view method to create a new array object that looks at the same data as the original array (a shallow copy).
Views are an important NumPy concept! NumPy functions, as well as operations like indexing and slicing, will return views whenever possible. This saves memory and is faster (no copy of the data has to be made). However it’s important to be aware of this — modifying data in a view also modifies the original array!
Let’s say you create this array:
Now we create an array b1 by slicing a and modify the first element of b1 . This will modify the corresponding element in a as well!
Using the copy method will make a complete copy of the array and its data (a deep copy). To use this on your array, you could run:
Basic array operations#
This section covers addition, subtraction, multiplication, division, and more
Once you’ve created your arrays, you can start to work with them. Let’s say, for example, that you’ve created two arrays, one called “data” and one called “ones”

You can add the arrays together with the plus sign.

You can, of course, do more than just addition!

Basic operations are simple with NumPy. If you want to find the sum of the elements in an array, you’d use sum() . This works for 1D arrays, 2D arrays, and arrays in higher dimensions.
To add the rows or the columns in a 2D array, you would specify the axis.
If you start with this array:
You can sum over the axis of rows with:
You can sum over the axis of columns with:
Broadcasting#
There are times when you might want to carry out an operation between an array and a single number (also called an operation between a vector and a scalar) or between arrays of two different sizes. For example, your array (we’ll call it “data”) might contain information about distance in miles but you want to convert the information to kilometers. You can perform this operation with:

NumPy understands that the multiplication should happen with each cell. That concept is called broadcasting. Broadcasting is a mechanism that allows NumPy to perform operations on arrays of different shapes. The dimensions of your array must be compatible, for example, when the dimensions of both arrays are equal or when one of them is 1. If the dimensions are not compatible, you will get a ValueError .
More useful array operations#
This section covers maximum, minimum, sum, mean, product, standard deviation, and more
NumPy also performs aggregation functions. In addition to min , max , and sum , you can easily run mean to get the average, prod to get the result of multiplying the elements together, std to get the standard deviation, and more.

Let’s start with this array, called “a”
It’s very common to want to aggregate along a row or column. By default, every NumPy aggregation function will return the aggregate of the entire array. To find the sum or the minimum of the elements in your array, run:
You can specify on which axis you want the aggregation function to be computed. For example, you can find the minimum value within each column by specifying axis=0 .
The four values listed above correspond to the number of columns in your array. With a four-column array, you will get four values as your result.
Creating matrices#
You can pass Python lists of lists to create a 2-D array (or “matrix”) to represent them in NumPy.

Indexing and slicing operations are useful when you’re manipulating matrices:

You can aggregate matrices the same way you aggregated vectors:

You can aggregate all the values in a matrix and you can aggregate them across columns or rows using the axis parameter. To illustrate this point, let’s look at a slightly modified dataset:

Once you’ve created your matrices, you can add and multiply them using arithmetic operators if you have two matrices that are the same size.

You can do these arithmetic operations on matrices of different sizes, but only if one matrix has only one column or one row. In this case, NumPy will use its broadcast rules for the operation.

Be aware that when NumPy prints N-dimensional arrays, the last axis is looped over the fastest while the first axis is the slowest. For instance:
There are often instances where we want NumPy to initialize the values of an array. NumPy offers functions like ones() and zeros() , and the random.Generator class for random number generation for that. All you need to do is pass in the number of elements you want it to generate:

You can also use ones() , zeros() , and random() to create a 2D array if you give them a tuple describing the dimensions of the matrix:

Read more about creating arrays, filled with 0 ’s, 1 ’s, other values or uninitialized, at array creation routines .
Generating random numbers#
The use of random number generation is an important part of the configuration and evaluation of many numerical and machine learning algorithms. Whether you need to randomly initialize weights in an artificial neural network, split data into random sets, or randomly shuffle your dataset, being able to generate random numbers (actually, repeatable pseudo-random numbers) is essential.
With Generator.integers , you can generate random integers from low (remember that this is inclusive with NumPy) to high (exclusive). You can set endpoint=True to make the high number inclusive.
You can generate a 2 x 4 array of random integers between 0 and 4 with:
How to get unique items and counts#
This section covers np.unique()
You can find the unique elements in an array easily with np.unique .
For example, if you start with this array:
you can use np.unique to print the unique values in your array:
To get the indices of unique values in a NumPy array (an array of first index positions of unique values in the array), just pass the return_index argument in np.unique() as well as your array.
You can pass the return_counts argument in np.unique() along with your array to get the frequency count of unique values in a NumPy array.
This also works with 2D arrays! If you start with this array:
You can find unique values with:
If the axis argument isn’t passed, your 2D array will be flattened.
If you want to get the unique rows or columns, make sure to pass the axis argument. To find the unique rows, specify axis=0 and for columns, specify axis=1 .
To get the unique rows, index position, and occurrence count, you can use:
To learn more about finding the unique elements in an array, see unique .
Transposing and reshaping a matrix#
This section covers arr.reshape() , arr.transpose() , arr.T
It’s common to need to transpose your matrices. NumPy arrays have the property T that allows you to transpose a matrix.

You may also need to switch the dimensions of a matrix. This can happen when, for example, you have a model that expects a certain input shape that is different from your dataset. This is where the reshape method can be useful. You simply need to pass in the new dimensions that you want for the matrix.

You can also use .transpose() to reverse or change the axes of an array according to the values you specify.
NumPy #
Первая сторонняя библиотека, с которой мы познакомимся — NumPy (Numerical Python).
Библиотека NumPy предоставляет доступ к многомерным массивам однородных данных (одного типа, обычно числа), подобным массивам C/C++ , и к методам их обработки. Под капотом эти самые массивы реализованы с помощью динамических массивов C , которые в отличие от списков хранят непосредственно данные, а не указатели на них.
Зачем нужен NumPy #
Необходимость в специальной библиотеке для работы с большими массивами чисел возникает из-за скорости работы python . За гибкость, выразительность, динамическую типизацию и многие другие достоинства python приходится платить скоростью: код написанный на python , практически всегда будет работать медленнее, чем аналогичный код, написанный на C/C++ . Проще всего продемонстрировать это на примере с громоздкими циклами.
Документацию по модулю time можно найти по этой ссылке, а по модулю random по этой ссылке.
Выше приведено содержимое двух файлов с исходным кодом, каждый из которых складывает два вектора чисел размерности \(10^8\) .
Первый файл на языке C++ использует для представления векторов в программе std::vector.
Второй файл на языке python использует для представления векторов в программе списки.
Эти файлы располагаются по ссылке и могут быть запущены следующими командами в командной строке.
В среднем я получил следующие результаты.
Вообще говоря, на эти цифры может повлиять огромное количество факторов, в том числе и случайных. Тем не менее разница настолько явная, что качественная картина ясна: циклы в C/C++ работают заметно быстрее, чем в python .
“Среднее” приложение на python не сталкивается с обработкой больших объемов данных и обычно разница в производительности компенсируется затраченным на реализацию алгоритма временем. Но научные вычисления очень часто представляют собой “программы по перемолке чисел” и такое замедление существенно.
Чтобы совместить скорость компилируемого языка и удобство python многие библиотеки поставляются вместе со скомпилированными модулями, написанными на C/C++ (или другом компилируемом языке), а в python “прокидывают” интерфейс для взаимодействия с ними. NumPy — яркий пример такой библиотеки.
Установка NumPy #
В anaconda NumPy установлен по умолчанию, а установить его с помощью PyPI можно следующей командой.
Установив NumPy , чтобы пользоваться им в программе, необходимо его импортировать.
Библиотека NumPy используется настолько часто и настолько многими, что сложилась традиция импортировать NumPy с псевдонимом np . Любой программист, увидев где-то в коде выражение вида np.some_method() догадается, что вызывается метод some_method из библиотеки NumPy и ему не потребуется искать глазами определение объекта np , чтобы понять, что скрывается за этим именем.
О массивах NumPy . Тип данных, размерность, оси и форма.#
В ячейке ниже создаётся массив NumPy из случайных чисел. Можете пока не вникать, как конкретно он создаётся. Важно лишь понять, что имя array связывается с каким-то массивом NumPy .
Массивы в библиотеке представляются типом numpy.ndarray (n dimensional array, n-мерный массив).
Тип ndarray является типизированным контейнером данных, т.е. он предназначен для хранения данных одного и того же типа данных. Тип данных массива хранится в атрибуте dtype (data type). Этих типов может быть много, но большинство из них — стандартные числовые типы C/C++ : np.bool8 , np.int8 , np.int16 , np.int32 , np.int64 , np.unit8 , np.unit16 , np.unit32 , np.uint64 , np.float16 , np.float32 , np.float64 , np.complex64 , np.complex128 (подробнее про типы данных).
Целые числа в массивах NumPy введут себя совсем не как тип int из python : они всегда занимают определенное количество байт и могут переполняться, т.е. совпадают с целочисленными типами из C/C++ .
Вообще говоря, в массивах NumPy можно хранить и объекты произвольного типа, но тогда вместо самих объектов, в массиве будут храниться ссылки на них. Чаще всего массивы NumPy используются все же для хранения чисел.
Исходя из значения атрибута dtype массива array можно понять, что он хранит в себе 64-битные числа с плавающей запятой.
Ещё NumPy массивы хранят количество своих измерений в атрибуте ndim (number of dimensions). Массивы NumPy могут быть любой размерности: одномерные массивы часто используются для представления векторов, двумерные — для представления матриц и таблиц, массивы более высоких размерностей — для представления тензоров, массивы любых размерностей часто используются для представления значений некоторой функции векторного аргумента на сетке в многомерном пространстве.
Исходя из значения атрибута ndim массива array видим, что он является двухмерным.
Ещё обязательный атрибут массивов NumPy — форма ( shape ) — размеры массива вдоль каждого измерения. Эти измерения называются осями ( axis в ед. числе и axes в мн. числе).
Атрибут shape массива array говорит нам, что у него есть 2 элемента вдоль первого измерения и 3 вдоль второго. Иными словами можно сказать, что это таблица из двух строк и трех столбцов.
Общее количество элементов в массиве (произведение количеств элементов вдоль каждой из осей) хранится в атрибуте size .
Все массивы должны быть выравненными, т.е. не может быть матрицы со строками разных длин, трехмерного массива из матриц разных размеров и т.п.
Картинка ниже наглядно иллюстрирует смысл всех только что введенных понятий.

Создание массивов#
Создавать массивы NumPy — ndarray — можно огромным количеством образом, но для их создания редко используется конструктор самого типа. Вместо этого гораздо чаще используются другие методы. Например, метод numpy.array конструирует ndarray из других объектов.
Чаще всего он используется для создания массивов NumPy из python списков чисел. Тип данных выводится как самый общий тип данных, если он не указан явно именованным параметром dtype .
Ниже создаётся одномерный массив из списка четырёх чисел. При этом тип данных явно не указывается и в итоге получается массив чисел с плавающей точкой ( float64 ), т.к. в исходном списке были числа типа int и float .
В ячейке ниже демонстрируется, как создаются двухмерные массивы. Для этого ей на вход передаются списки списков, где каждый вложенный список — строка будущей таблицы. Т.к. внутри всех этих списков находятся только целые числа, то итоговый тип массива тоже целочисленный.
Трехмерные массивы создаются по аналогии. В ячейке ниже приводится пример. Обратите внимание, что все числа в передаваемом списке списков списков целочисленного типа, но результирующий массив получается типа float32 , т.к. этот тип явно указан при создании массива.
Так же есть ряд встроенных функций, создающих массивы. Каждая из них принимает в качестве опционального аргумента dtype .
start , stop , end
Аналог np.array(range) , но можно использовать float в качестве аргументов
start , stop , num , endpoint=True
Разбиение отрезка [ start , stop ] на num отрезков, если передать в качестве endpoint=False , то последняя точка не включается
Массив заданной формы из нулей
Массив заданной формы из единиц
Не метод, а подмодуль, содержащий методы создания массивов случайных значений
Если m не указан, то квадратная единичная матрица размера nxn , иначе нулевая матрица размера nxm с единицами на диагонали
NumPy в Python. Часть 1
Доброго времени суток, Хабр. Запускаю цикл статей, которые являются переводом небольшого мана по numpy, ссылочка. Приятного чтения.
Введение
Установка
Если у вас есть Python(x, y) (Примечание переводчика: Python(x, y), это дистрибутив свободного научного и инженерного программного обеспечения для численных расчётов, анализа и визуализации данных на основе языка программирования Python и большого числа модулей (библиотек)) на платформе Windows, то вы готовы начинать. Если же нет, то после установки python, вам нужно установить пакеты самостоятельно, сначала NumPy потом SciPy. Установка доступна здесь. Следуйте установке на странице, там всё предельно понятно.
Немного дополнительной информации
Сообщество NumPy и SciPy поддерживает онлайн руководство, включающие гайды и туториалы, тут: docs.scipy.org/doc.
Импорт модуля numpy
Есть несколько путей импорта. Стандартный метод это — использовать простое выражение:
Тем не менее, для большого количества вызовов функций numpy, становится утомительно писать numpy.X снова и снова. Вместо этого намного легче сделать это так:
Это выражение позволяет нам получать доступ к numpy объектам используя np.X вместо numpy.X. Также можно импортировать numpy прямо в используемое пространство имен, чтобы вообще не использовать функции через точку, а вызывать их напрямую:
Однако, этот вариант не приветствуется в программировании на python, так как убирает некоторые полезные структуры, которые модуль предоставляет. До конца этого туториала мы будем использовать второй вариант импорта (import numpy as np).
Массивы
Главной особенностью numpy является объект array. Массивы схожи со списками в python, исключая тот факт, что элементы массива должны иметь одинаковый тип данных, как float и int. С массивами можно проводить числовые операции с большим объемом информации в разы быстрее и, главное, намного эффективнее чем со списками.
Создание массива из списка:
Здесь функция array принимает два аргумента: список для конвертации в массив и тип для каждого элемента. Ко всем элементам можно получить доступ и манипулировать ими так же, как вы бы это делали с обычными списками:
Массивы могут быть и многомерными. В отличии от списков можно использовать запятые в скобках. Вот пример двумерного массива (матрица):
Array slicing работает с многомерными массивами аналогично, как и с одномерными, применяя каждый срез, как фильтр для установленного измерения. Используйте ":" в измерении для указывания использования всех элементов этого измерения:
Метод shape возвращает количество строк и столбцов в матрице:
Метод dtype возвращает тип переменных, хранящихся в массиве:
Тут float64, это числовой тип данных в numpy, который используется для хранения вещественных чисел двойной точности. Так же как float в Python.
Метод len возвращает длину первого измерения (оси):
Метод in используется для проверки на наличие элемента в массиве:
Массивы можно переформировать при помощи метода, который задает новый многомерный массив. Следуя следующему примеру, мы переформатируем одномерный массив из десяти элементов во двумерный массив, состоящий из пяти строк и двух столбцов:
Обратите внимание, метод reshape создает новый массив, а не модифицирует оригинальный.
Имейте ввиду, связывание имен в python работает и с массивами. Метод copy используется для создания копии существующего массива в памяти:
Списки можно тоже создавать с массивов:
Можно также переконвертировать массив в бинарную строку (то есть, не human-readable форму). Используйте метод tostring для этого. Метод fromstring работает в для обратного преобразования. Эти операции иногда полезны для сохранения большого количества данных в файлах, которые могут быть считаны в будущем.
Заполнение массива одинаковым значением.
Транспонирование массивов также возможно, при этом создается новый массив:
Многомерный массив можно переконвертировать в одномерный при помощи метода flatten:
Два или больше массивов можно сконкатенировать при помощи метода concatenate:
Если массив не одномерный, можно задать ось, по которой будет происходить соединение. По умолчанию (не задавая значения оси), соединение будет происходить по первому измерению:
В заключении, размерность массива может быть увеличена при использовании константы newaxis в квадратных скобках:
Заметьте, тут каждый массив двумерный; созданный при помощи newaxis имеет размерность один. Метод newaxis подходит для удобного создания надлежаще-мерных массивов в векторной и матричной математике.