numpy数组的重塑和转置如何实现

其他教程   发布日期:2024年04月26日   浏览次数:48

这篇文章主要介绍“numpy数组的重塑和转置如何实现”,在日常操作中,相信很多人在numpy数组的重塑和转置如何实现问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”numpy数组的重塑和转置如何实现”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

一.一维数组的转置

描述

  • 一维数组的重塑就是将一行或一列的数组转换为多行多列的数组

  • 重塑之后的数组应于原有数组形状兼容(数组元素应该相等)

用法和参数

  • 数组.reshape(x,y)

    • x:转换后数组的行数

    • y:转换后数组的列数

实例

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
# 将数组重塑为2行4列的形状
a = arr.reshape(2, 4)
# 将数组重塑为4行2列的形状
b = arr.reshape(4, 2)

print(a)
'''
[[1 2 3 4]
 [5 6 7 8]]
'''
print(b)
'''
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
'''

二.多为数组的重塑

描述

  • 多维数组的重塑就是改变多维数组的形状

用法和参数

  • 数组.reshape(x,y)

    • x:转换后数组的行数

    • y:转换后数组的列数

实例

import numpy as np

arr = np.array(
    [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]
    ]
)
# 将数组重塑为4行3列的形状
a = arr.reshape(4, 3)
# 将数组重塑为2行6列的形状
b = arr.reshape(2, 6)
print(a)
'''
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
'''
print(b)
'''
[[ 1  2  3  4  5  6]
 [ 7  8  9 10 11 12]]
'''

三.将多维数组转换为一维数组

用法和参数

  • 数组.flatten()

  • 数组.ravel()

实例

import numpy as np

arr = np.array(
    [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]
    ]
)
# 将数组转换为一维数组
print(arr.flatten())
'''
[ 1  2  3  4  5  6  7  8  9 10 11 12]
'''
# 将数组转换为一维数组
print(arr.ravel())
'''
[ 1  2  3  4  5  6  7  8  9 10 11 12]
'''

四.数组的转置

描述

  • 将数组的行变成列,列变成行

用法和参数

  • T属性

  • transpose()

实例

import numpy as np

arr = np.array(
    [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]
    ]
)
# 对数组进行转置
print(arr.T)
'''
[[ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]
 [ 4  8 12]]
'''
# 对数组进行转置
print(arr.transpose())
'''
[[ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]
 [ 4  8 12]]
'''

以上就是numpy数组的重塑和转置如何实现的详细内容,更多关于numpy数组的重塑和转置如何实现的资料请关注九品源码其它相关文章!