Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python numpy roll with padding

I'd like to roll a 2D numpy in python, except that I'd like pad the ends with zeros rather than roll the data as if its periodic.

Specifically, the following code

import numpy as np  x = np.array([[1, 2, 3], [4, 5, 6]])  np.roll(x, 1, axis=1) 

returns

array([[3, 1, 2],[6, 4, 5]]) 

but what I would prefer is

array([[0, 1, 2], [0, 4, 5]]) 

I could do this with a few awkward touchups, but I'm hoping that there's a way to do it with fast built-in commands.

Thanks

like image 341
marshall.ward Avatar asked May 06 '10 01:05

marshall.ward


People also ask

How do you add padding to an array in Python?

pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy. pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width.

How do I roll a NumPy array?

The numpy. roll() function rolls array elements along the specified axis. Basically what happens is that elements of the input array are being shifted. If an element is being rolled first to the last position, it is rolled back to the first position.

What is padding an array?

The array padding transformation sets a dimension in an array to a new size. The goal of this transformation is to reduce the number of memory system conflicts. The transformation is applied to a full function AST. The new size can be specified by the user or can be computed automatically.


2 Answers

There is a new numpy function in version 1.7.0 numpy.pad that can do this in one-line. Pad seems to be quite powerful and can do much more than a simple "roll". The tuple ((0,0),(1,0)) used in this answer indicates the "side" of the matrix which to pad.

import numpy as np x = np.array([[1, 2, 3],[4, 5, 6]])  print np.pad(x,((0,0),(1,0)), mode='constant')[:, :-1] 

Giving

[[0 1 2]  [0 4 5]] 
like image 151
Hooked Avatar answered Sep 21 '22 23:09

Hooked


I don't think that you are going to find an easier way to do this that is built-in. The touch-up seems quite simple to me:

y = np.roll(x,1,axis=1) y[:,0] = 0 

If you want this to be more direct then maybe you could copy the roll function to a new function and change it to do what you want. The roll() function is in the site-packages\core\numeric.py file.

like image 30
Justin Peel Avatar answered Sep 24 '22 23:09

Justin Peel