Answers for "np.pad 2d array"

3

python how to pad a numpy array with zeros

# Basic syntax:
# For 1D array:
np.pad(numpy_array, (pad_left, pad_right), 'constant')

# For 2D array:
np.pad(numpy_array, ((pad_top, pad_bottom), (pad_left, pad_right)), 'constant')

# Example usage:
import numpy as np
numpy_array = np.array([1,2,3,4,5]) # 1D array
np.pad(numpy_array, (2, 3), 'constant') # Pad 2 left, 3 right
--> array([0, 0, 1, 2, 3, 4, 5, 0, 0, 0])

numpy_array = np.array([[1,2],[3,4]]) # 2D array
array([[1, 2], # Before padding
       [3, 4]])
np.pad(numpy_array, ((1,2),(2,1)), 'constant') # Pad 1 top, 2 bottom, 2 left, 1 right
array([[0, 0, 0, 0, 0], # After padding
       [0, 0, 1, 2, 0],
       [0, 0, 3, 4, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
Posted by: Guest on October-04-2020
2

np.pad

>>> np.pad(a, [(1, ), (2, )], mode='constant')
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
Posted by: Guest on September-11-2020
-2

numpy convert 1d array to 2d

import numpy as np 

# 1D array 
one_dim_arr = np.array([1, 2, 3, 4, 5, 6])

# to convert to 2D array
# we can use the np.ndarray.reshape(shape) function 
# here shape is given by two integers seperated by a comma
# the two integers specify m,n for the new matrix 
# ensure that the matrix that you are trying to generate
# has a size that meets the number of elements in the 1D array. 
# for that make sure that 
# m * n = number of elements in the one dimentional array 

two_dim_arr = one_dim_arr.reshape(1, 6)

#which returns a 2D array
print(two_dim_arr)


# confirmed by the array.ndim attribute
print(two_dim_arr.ndim)

# you can even specify one of the dimensions as unknown by passing -1
# numpy will infer the length using the array and remaining dimensions

two_dim_arr = one_dim_arr.reshape(1,-1)
Posted by: Guest on November-14-2020
-1

numpy make 2d array 1d

import numpy as np
  
ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])
  
# printing initial arrays
print("initial array", str(ini_array1))
  
# Multiplying arrays
result = ini_array1.flatten()
  
# printing result
print("New resulting array: ", result)
Posted by: Guest on July-24-2021

Python Answers by Framework

Browse Popular Code Answers by Language