Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to extend a numpy array in 2 dimensions?

I have a 2d array that looks like this:

XX xx 

What's the most efficient way to add an extra row and column:

xxy xxy yyy 

For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible:

xxaxx xxaxx aaaaa xxaxx xxaxx 
like image 245
Salim Fadhley Avatar asked May 18 '09 12:05

Salim Fadhley


People also ask

How do you make a NumPy array 2-dimensional?

In Python to declare a new 2-dimensional array we can easily use the combination of arange and reshape() method. The reshape() method is used to shape a numpy array without updating its data and arange() function is used to create a new array.

How do you expand the dimension of a NumPy array?

You can add new dimensions to a NumPy array ndarray (= unsqueeze a NumPy array) with np. newaxis , np. expand_dims() and np. reshape() (or reshape() method of ndarray ).

What is a 2-dimensional NumPy array?

2D array are also called as Matrices which can be represented as collection of rows and columns. In this article, we have explored 2D array in Numpy in Python. NumPy is a library in python adding support for large multidimensional arrays and matrices along with high level mathematical functions to operate these arrays.

Can NumPy arrays have more than 2 dimensions?

Creating arrays with more than one dimensionIn general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.


1 Answers

The shortest in terms of lines of code i can think of is for the first question.

>>> import numpy as np >>> p = np.array([[1,2],[3,4]])  >>> p = np.append(p, [[5,6]], 0) >>> p = np.append(p, [[7],[8],[9]],1)  >>> p array([[1, 2, 7],    [3, 4, 8],    [5, 6, 9]]) 

And the for the second question

    p = np.array(range(20)) >>> p.shape = (4,5) >>> p array([[ 0,  1,  2,  3,  4],        [ 5,  6,  7,  8,  9],        [10, 11, 12, 13, 14],        [15, 16, 17, 18, 19]]) >>> n = 2 >>> p = np.append(p[:n],p[n+1:],0) >>> p = np.append(p[...,:n],p[...,n+1:],1) >>> p array([[ 0,  1,  3,  4],        [ 5,  6,  8,  9],        [15, 16, 18, 19]]) 
like image 166
tomeedee Avatar answered Sep 22 '22 12:09

tomeedee