有多种创建numpy数组的方法。Numpy提供了两种将ndarray转换为1Darray的flatten()
方法:一种是使用方法,另一种是使用ravel()
方法。
#Import required library, numpy import numpy as np #create an array from a list arr = np.array( [ (2, 7, 3, 4), (5, 6, 9, 1)]) #flatten_output print(arr.flatten()) #ravel_output print(arr.ravel())
输出结果
[2 7 3 4 5 6 9 1] [2 7 3 4 5 6 9 1]
现在,在上面我们可以看到两个函数返回相同的列表,因此出现了一个问题,为什么两个方法用于同一任务?
以下是flatten()
和ravel()
方法之间的主要区别。
返回原始数组的唯一引用
修改上面的array(arr)后,我们可以看到原始数组的值也发生了变化。
因为ravel方法确实占用了任何内存,所以ravel比 flatten()
Ravel是库级别的函数
返回array(arr)的原始副本。
在修改上述数组(arr)时,原始数组的值不会更改。
因为flatten()
占用内存,flatten()
比慢一点ravel()
这是ndarray对象的方法。
#Import required library, numpy import numpy as np # Create a numpy array, arr arr = np.array([(1,2,3,4),(3,1,4,2)]) # Let's print the array arr print ("Original array:\n ", arr) #print(arr) # To check the dimension of array (dimension =2) and type is numpy.ndarray print ("Dimension of original array: %d \n Type of original array: %s" % (arr.ndim,type(arr))) print("\nOutput from ravel method: \n") # Convert nd array to 1D array b_arr = arr.ravel() # Ravel only passes a view of original array to array 'b_arr' print(b_arr) b_arr[0]=1000 print(b_arr) # Note here that value of original array 'arr' at also arr[0][0] becomes 1000 print(arr) # Just to check the dimension i.e. 1 and type is same numpy.ndarray print ("Dimension of array: %d \n Type of array: %s" % (b_arr.ndim,type(b_arr))) print("\nOutput from flatten method: \n") # Convert nd array to 1D array c_arr = arr.flatten() # Flatten passes copy of original array to 'c_arr' print(c_arr) c_arr[0]=0 print(c_arr) # Note that by changing value of c_arr there is no affect on value of original array 'arr' print(arr) print ("Dimension of array->%d \n Type of array->%s" % (c_arr.ndim,type(c_arr)))
输出结果
Original array: [[1 2 3 4] [3 1 4 2]] Dimension of original array: 2 Type of original array: <class 'numpy.ndarray'> Output from ravel method: [1 2 3 4 3 1 4 2] [1000 2 3 4 3 1 4 2] [[1000 2 3 4] [ 3 1 4 2]] Dimension of array: 1 Type of array: <class 'numpy.ndarray'> Output from flatten method: [1000 2 3 4 3 1 4 2] [0 2 3 4 3 1 4 2] [[1000 2 3 4] [ 3 1 4 2]] Dimension of array->1 Type of array-><class 'numpy.ndarray'>