Как добавить строку в матрицу в NumPy (с примерами)
Вы можете использовать следующий синтаксис для добавления строки в матрицу в NumPy:
Вы также можете использовать следующий синтаксис, чтобы добавлять в матрицу только те строки, которые соответствуют определенному условию:
В следующих примерах показано, как использовать этот синтаксис на практике.
Пример 1: добавить строку в матрицу в NumPy
Следующий код показывает, как добавить новую строку в матрицу в NumPy:
Обратите внимание, что последняя строка успешно добавлена в матрицу.
Пример 2. Добавление строк в матрицу на основе условия
В следующем коде показано, как добавить несколько новых строк в существующую матрицу на основе определенного условия:
Добавлялись только строки, в которых первый элемент в строке был меньше 10.
Примечание.Полную онлайн-документацию по функции vstack() можно найти здесь .
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные операции в NumPy:
Numpy — add row to array
I wish to add rows to this array from another array X if the first element of each row in X meets a specific condition.
Numpy arrays do not have a method ‘append’ like that of lists, or so it seems.
If A and X were lists I would merely do:
Is there a numpythonic way to do the equivalent?
10 Answers 10
You can do this:
![]()
What is X ? If it is a 2D-array, how can you then compare its row to a number: i < 3 ?
EDIT after OP’s comment:
add to A all rows from X where the first element < 3 :
![]()
As this question is been 7 years before, in the latest version which I am using is numpy version 1.13, and python3, I am doing the same thing with adding a row to a matrix, remember to put a double bracket to the second argument, otherwise, it will raise dimension error.
In here I am adding on matrix A
same usage in np.r_
Just to someone’s intersted, if you would like to add a column,
array = np.c_[A,np.zeros(#A’s row size)]
following what we did before on matrix A, adding a column to it
If you want to prepend, you can just flip the order of the arguments, i.e.:
If no calculations are necessary after every row, it’s much quicker to add rows in python, then convert to numpy. Here are timing tests using python 3.6 vs. numpy 1.14, adding 100 rows, one at a time:
So, the simple solution to the original question, from seven years ago, is to use vstack() to add a new row after converting the row to a numpy array. But a more realistic solution should consider vstack’s poor performance under those circumstances. If you don’t need to run data analysis on the array after every addition, it is better to buffer the new rows to a python list of rows (a list of lists, really), and add them as a group to the numpy array using vstack() before doing any data analysis.
Add Row to Matrix in NumPy

Matrices are often used in mathematics and statistics for data representation and solving multiple linear equations. In programming, a 2-Dimensional array is treated as a matrix.
In Python, the numpy module is used to work with arrays. It has many functions and classes available for performing different operations on matrices.
In this tutorial, we will learn how to add a row to a matrix in numpy.
Use the numpy.vstack() Function to Add a Row to a Matrix in NumPy
The vstack() function stacks arrays vertically. Stacking two 2D arrays vertically is equivalent to adding rows to a matrix.
The following code shows this.
Use the numpy.append() Function to Add a Row to a Matrix in NumPy
The append() function from the numpy module can add elements to the end of the array. By specifying the axis as 0, we can use this function to add rows to a matrix.
Use the numpy.r_() Function to Add a Row to a Matrix in NumPy
The r_() function from the numpy module concatenates arrays by combining them vertically.
Check the code below to see how we can use this to add rows to a matrix.
Alternatively, we can use the concatenate() function, too. The concatenate() function combines two or more arrays so it can be used to achieve the desired result.
Use the numpy.insert() Function to Add a Row to a Matrix in NumPy
The insert() function adds objects along the specified axis and the position. It can be used to insert a row in a matrix at our desired specific position.
In the above code, we add the row at the end of the matrix. The shape() function returns the array’s dimensions, which reveals the total number of rows in the matrix.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
numpy.append#
These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.
axis int, optional
The axis along which values are appended. If axis is not given, both arr and values are flattened before use.
Returns : append ndarray
A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.
Insert elements into an array.
Delete elements from an array.
When axis is specified, values must have the correct shape.