當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python numpy.ravel()用法及代碼示例


關於:
numpy.ravel(array,order ='C'):返回連續的扁平化數組(具有所有input-array元素且類型相同的一維數組)。僅在需要時才進行複製。

參數:

array : [array_like]Input array. 
order : [C-contiguous, F-contiguous, A-contiguous; optional]         
         C-contiguous order in memory(last index varies the fastest)
         C order means that operating row-rise on the array will be slightly quicker
         FORTRAN-contiguous order in memory (first index varies the fastest).
         F order means that column-wise operations will be faster. 
         ‘A’ means to read / write the elements in Fortran-like index order if,
         array is Fortran contiguous in memory, C-like order otherwise

返回:


Flattened array having same type as the Input array and and order as per choice. 

代碼1:顯示array.ravel等效於reshape(-1,order = order)

# Python Program illustrating 
# numpy.ravel() method 
  
import numpy as geek 
  
array = geek.arange(15).reshape(3, 5) 
print("Original array : \n", array) 
  
# Outpue comes like [ 0  1  2 ..., 12 13 14] 
# as it is a long output, so it is the way of 
# showing outptut in Python 
print("\nravel() : ", array.ravel()) 
  
# This shows array.ravel is equivalent to reshape(-1, order=order). 
print("\nnumpy.ravel() == numpy.reshape(-1)") 
print("Reshaping array : ", array.reshape(-1))

輸出:

Original array : 
 [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]

ravel() :  [ 0  1  2 ..., 12 13 14]

numpy.ravel() == numpy.reshape(-1)
Reshaping array :  [ 0  1  2 ..., 12 13 14]

代碼2:顯示排序操作

# Python Program illustrating 
# numpy.ravel() method 
  
import numpy as geek 
  
array = geek.arange(15).reshape(3, 5) 
print("Original array : \n", array) 
  
# Outpue comes like [ 0  1  2 ..., 12 13 14] 
# as it is a long output, so it is the way of 
# showing outptut in Python 
  
# About :  
print("\nAbout numpy.ravel() : ", array.ravel) 
  
print("\nnumpy.ravel() : ", array.ravel()) 
  
# Maintaining both 'A' and 'F' order 
print("\nMaintains A Order : ", array.ravel(order = 'A')) 
  
# K-order preserving the ordering 
# 'K' means that is neither 'A' nor 'F' 
array2 = geek.arange(12).reshape(2,3,2).swapaxes(1,2) 
print("\narray2 \n", array2) 
print("\nMaintains A Order : ", array2.ravel(order = 'K'))

輸出:

Original array : 
 [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]

About numpy.ravel() :  

numpy.ravel() :  [ 0  1  2 ..., 12 13 14]

Maintains A Order :  [ 0  1  2 ..., 12 13 14]

array2 
 [[[ 0  2  4]
  [ 1  3  5]]

 [[ 6  8 10]
  [ 7  9 11]]]

Maintains A Order :  [ 0  1  2 ...,  9 10 11]

參考文獻:
https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.ravel.html#numpy.ravel



相關用法


注:本文由純淨天空篩選整理自 numpy.ravel() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。