python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > numpy展平数组ndarray.flatten()

numpy展平数组ndarray.flatten()详解

作者:大Py

这篇文章主要介绍了numpy展平数组ndarray.flatten()详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

numpy展平数组ndarray.flatten()

ndarray.flatten(order=‘C')

复制原数组,并将其展平成一维数组返回。

Params:

order : {‘C’, ‘F’, ‘A’, ‘K’},可选任意一个,默认是‘C’。

举例,原始数组:

arr = np.arange(9).reshape(3,3)
arr
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

按‘C’风格展平:

arr.flatten()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])

按’F’风格展平:

arr.flatten('F')
array([0, 3, 6, 1, 4, 7, 2, 5, 8])

numpy.ndarray实现扁平化numpy.ndarray.flatten

numpy.ndarray.flatten(order=‘C')

官方链接

把多维数组"扁平化"为一个一维向量,其过程是把该数组按照order指定的顺序遍历一遍,并把结果储存为一维向量.

Parameters
order {‘C', ‘F', ‘A', ‘K'}, optional
‘C' (Default) 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'.

示例

a = np.array([[1,2], [3,4]])
print(a.flatten())

结果

[1 2 3 4]

相当于

print(a.reshape(1,a.size))

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文