Python numpy.ravel()

Python numpy.ravel()

Python numpy.ravel()函数返回连续的扁平数组(具有所有输入数组元素且类型相同的1D数组)。只有在需要时才会复制。
语法 :

numpy.ravel(array, order = 'C')

参数 :

array : [array_like]输入阵列。
order : [C-contiguous, F-contiguous, A-contiguous; optional] C-contiguous顺序在内存中(最后一个索引变化最快)C顺序意味着在数组上操作行上升会稍微快一些 FORTRAN-contiguous顺序在内存中(第一个索引变化最快)。F顺序意味着对列的操作会更快。A’意味着如果阵列在内存中是FORTRAN连续的,则以类似FORTRAN的索引顺序读/写元素,否则以类似C的顺序读/写元素

返回 :

扁平化的数组,其类型与输入数组相同,并按选择顺序排列。

**代码1:显示array.ravel等同于reshape(-1, order=order) **

# Python Program illustrating
# numpy.ravel() method
 
import numpy as geek
 
array = geek.arrange(15).reshape(3, 5)
print("Original array : \n", array)
 
# Output comes like [ 0  1  2 ..., 12 13 14]
# as it is a long output, so it is the way of
# showing output 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.arrange(15).reshape(3, 5)
print("Original array : \n", array)
 
# Output comes like [ 0  1  2 ..., 12 13 14]
# as it is a long output, so it is the way of
# showing output 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.arrange(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]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程