[Python Cookbook] Numpy: How to Apply a Function to 1D Slices along the Given Axis

Here is a function in Numpy module which could apply a function to 1D slices along the Given Axis. It works like apply funciton in Pandas.

 

numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)

 

Parameters:
func1d function (M,) -> (Nj…)

This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis.

axis integer

Axis along which arr is sliced. (axis = 1: along the row; axis = 0: along the column)

arr ndarray (Ni…, M, Nk…)

Input array.

args any

Additional arguments to func1d.

kwargs any

Additional named arguments to func1d.

New in version 1.9.0.

Returns:
out ndarray (Ni…, Nj…, Nk…)

The output array. The shape of out is identical to the shape of arr, except along the axisdimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value of func1d. So if func1d returns a scalar out will have one fewer dimensions than arr.

Here is an example to shift the image one pixel down through numpy.apply_along_axis method.

1 import numpy as np
2 from scipy.ndimage.interpolation import shift
3 def shift_one_pixel(image, dx,dy):
4     image=image.reshape(28,28)
5     image_shifted=shift(image,[dy,dx],cval=0,mode='constant')
6     return image_shifted.reshape(28*28)
7 
8 X_train_expanded = np.apply_along_axis(shift_one_pixel,1,X_train,1,0)

 

posted @ 2019-01-01 10:42  Sherrrry  阅读(188)  评论(0编辑  收藏  举报