Answer a question

Is there a function doing the opposite of what numpy.pad() does?

What I am looking for is a function to (uniformly) reduce the dimensions of a numpy array (matrix) in each direction. I tried like to call the numpy.pad() with negative values, but it gave an error:

import numpy as np

A_flat = np.array([0,1,2,3,4,5,6,7,8,9,10,11])
A = np.reshape(A_flat, (3,2,-1))

#this WORKS:
B = np.pad(A, ((1,1),(1,1),(1,1)), mode='constant')

# this DOES NOT WORK:
C = np.pad(B, ((-1,1),(1,1),(1,1)), mode='constant')

Error: ValueError: ((-1, 1), (1, 1), (1, 1)) cannot contain negative values.

I understand this function numpy.pad() does not take negative values, but is there a numpy.unpad() or something similar?

Answers

Operation you want:

C = np.pad(B, ((-1,1),(1,1),(1,1)), mode='constant')

can be replaced with combination of pad and general slice:

C = np.pad(B, ((0,1),(1,1),(1,1)), mode='constant')[1:,...]
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐