當我們要從數組形狀中刪除一維條目時,將使用numpy.squeeze()函數。
用法: numpy.squeeze(arr, axis=None )
參數:
arr :[數組]輸入數組。
axis :[無,整數或整數元組,可選]選擇形狀中一維條目的子集。如果選擇的形狀輸入大於一個的軸,則會引發錯誤。
Return :
squeezed[ndarray]輸入數組,但刪除了長度為1的全部或部分維。這始終是其本身或對arr的看法。
代碼1:
# Python program explaining
# numpy.squeeze function
import numpy as geek
in_arr = geek.array([[[2, 2, 2], [2, 2, 2]]])
print ("Input array:", in_arr)
print("Shape of input array:", in_arr.shape)
out_arr = geek.squeeze(in_arr)
print ("output squeezed array:", out_arr)
print("Shape of output array:", out_arr.shape)
輸出:
Input array: [[[2 2 2] [2 2 2]]] Shape of input array: (1, 2, 3) output squeezed array: [[2 2 2] [2 2 2]] Shape of output array: (2, 3)
代碼2:
# Python program explaining
# numpy.squeeze function
import numpy as geek
in_arr = geek.arange(9).reshape(1, 3, 3)
print ("Input array:", in_arr)
out_arr = geek.squeeze(in_arr, axis = 0)
print ("output array:", out_arr)
print("The shapes of Input and Output array:")
print(in_arr.shape, out_arr.shape)
輸出:
Input array: [[[0 1 2] [3 4 5] [6 7 8]]] output array: [[0 1 2] [3 4 5] [6 7 8]] The shapes of Input and Output array: (1, 3, 3) (3, 3)
注意:
ValueError: If axis is not None, and an axis being squeezed is not of length 1.
代碼3:
# Python program explaining
# numpy.squeeze function
# when value error occurs
import numpy as geek
in_arr = geek.arange(9).reshape(1, 3, 3)
print ("Input array:", in_arr)
out_arr = geek.squeeze(in_arr, axis = 1)
print ("output array:", out_arr)
print("The shapes of Input and Output array:")
print(in_arr.shape, out_arr.shape)
輸出:
ValueError Traceback (most recent call last) in () 5 6 print ("Input array:", in_arr) ----> 7 out_arr = geek.squeeze(in_arr, axis=1) 8 print ("output array:", out_arr) 9 print("The shapes of Input and Output array:") ~\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in squeeze(a, axis) 1196 try: 1197 # First try to use the new axis= parameter -> 1198 return squeeze(axis=axis) 1199 except TypeError: 1200 # For backwards compatibility ValueError:cannot select an axis to squeeze out which has size not equal to one
相關用法
注:本文由純淨天空篩選整理自jana_sayantan大神的英文原創作品 numpy.squeeze() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。