numpy下的flatten()函數(shù)用法詳解
flatten是numpy.ndarray.flatten的一個函數(shù),其官方文檔是這樣描述的:
ndarray.flatten(order='C')
Return a copy of the array collapsed into one dimension.
Parameters:
|
order : {‘C', ‘F', ‘A', ‘K'}, optional ‘C' means to flatten in row-major (C-style) order. ‘F' means to flatten in column-major (Fortran- style) order. ‘A' means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K' means to flatten a in the order the elements occur in memory. The default is ‘C'. |
|
| Returns: |
y : ndarray A copy of the input array, flattened to one dimension. |
即返回一個折疊成一維的數(shù)組。但是該函數(shù)只能適用于numpy對象,即array或者mat,普通的list列表是不行的。
例子:
1、用于array對象
from numpy import * >>>a=array([[1,2],[3,4],[5,6]]) ###此時a是一個array對象 >>>a array([[1,2],[3,4],[5,6]]) >>>a.flatten() array([1,2,3,4,5,6])
2、用于mat對象
>>> a=mat([[1,2,3],[4,5,6]]) >>> a matrix([[1, 2, 3], [4, 5, 6]])<br>>>> a.flatten()<br>matrix([[1, 2, 3, 4, 5, 6]])<br>
3、但是該方法不能用于list對象
>>> a=[[1,2,3],[4,5,6],['a','b']] [[1, 2, 3], [4, 5, 6], ['a', 'b']] >>> a.flatten() ###報錯 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'flatten'
想要list達到同樣的效果可以使用列表表達式:
>>> [y for x in a for y in x] [1, 2, 3, 4, 5, 6, 'a', 'b']
4、用在矩陣
>>> a = [[1,3],[2,4],[3,5]] >>> a = mat(a) >>> y = a.flatten() >>> y matrix([[1, 3, 2, 4, 3, 5]]) >>> y = a.flatten().A >>> y array([[1, 3, 2, 4, 3, 5]]) >>> shape(y) (1, 6) >>> shape(y[0]) (6,) >>> y = a.flatten().A[0] >>> y array([1, 3, 2, 4, 3, 5])
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python連接PostgreSQL數(shù)據(jù)庫并查詢數(shù)據(jù)的詳細指南
在現(xiàn)代軟件開發(fā)中,數(shù)據(jù)庫是存儲和檢索數(shù)據(jù)的核心組件,PostgreSQ是一個功能強大的開源對象關(guān)系數(shù)據(jù)庫系統(tǒng),它以其穩(wěn)定性、強大的功能和靈活性而聞名,Python作為一種流行的編程語言,與PostgreSQL的結(jié)合使用非常廣泛,本文介紹了Python連接PostgreSQL數(shù)據(jù)庫并查詢數(shù)據(jù)2024-12-12
Pandas DataFrame操作數(shù)據(jù)增刪查改
我們在用 pandas 處理數(shù)據(jù)的時候,經(jīng)常會遇到用其中一列數(shù)據(jù)替換另一列數(shù)據(jù)的場景。這一類的需求估計很多人都遇到,當然還有其它更復雜的。解決這類需求的辦法有很多,這里我們來推薦幾個,這篇文章主要介紹了Pandas DataFrame操作數(shù)據(jù)的增刪查改2022-10-10

