numpy数组的重塑和转置实现
作者:飞Link 时间:2022-11-10 10:43:18
一.一维数组的转置
描述
一维数组的重塑就是将一行或一列的数组转换为多行多列的数组
重塑之后的数组应于原有数组形状兼容(数组元素应该相等)
用法和参数
数组.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]]
'''
来源:https://blog.csdn.net/feizuiku0116/article/details/119719282
标签:numpy,数组,重塑,转置
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python 队列基本定义与使用方法【初始化、赋值、判断等】
2023-08-13 06:34:46
![](https://img.aspxhome.com/file/2023/6/61476_0s.png)
pytest使用@pytest.mark.parametrize()实现参数化的示例代码
2022-07-17 07:54:01
![](https://img.aspxhome.com/file/2023/8/69508_0s.png)
利用Python实现简单的Excel统计函数
2021-09-27 09:21:09
![](https://img.aspxhome.com/file/2023/2/110072_0s.png)
Python数据结构与算法之图的广度优先与深度优先搜索算法示例
2022-05-05 07:34:53
asp如何定时执行约定的页面?
2009-11-15 20:17:00
MySQL之Explain详解
2024-01-12 21:14:55
![](https://img.aspxhome.com/file/2023/2/121582_0s.png)
HTTP头信息总结
2022-10-06 16:09:40
![](https://img.aspxhome.com/file/2023/5/131855_0s.jpg)
windows系统下让mysql支持federated的storage engine
2010-01-20 11:16:00
python 中的int()函数怎么用
2021-05-21 17:52:41
SQL 2008邮件故障排除:发送测试电子邮件
2008-12-02 14:28:00
django框架如何集成celery进行开发
2022-09-13 11:18:24
![](https://img.aspxhome.com/file/2023/4/67784_0s.png)
python面向对象实现名片管理系统文件版
2022-11-25 16:27:45
![](https://img.aspxhome.com/file/2023/1/104791_0s.png)
CentOS6.8使用cmake安装MySQL5.7.18
2024-01-27 06:00:06
基于Python列表解析(列表推导式)
2021-11-14 16:31:36
Python使用爬虫猜密码
2023-03-21 12:38:39
![](https://img.aspxhome.com/file/2023/6/67766_0s.png)
mysql 设置默认的时间值
2024-01-18 02:49:46
ASP中使用FileSystemObject时提高性能的一个小技巧
2008-06-08 13:09:00
调整Jupyter notebook的启动目录操作
2022-04-02 19:40:58
Python元组 tuple的概念与基本操作详解【定义、创建、访问、计数、推导式等】
2022-12-08 10:14:45
Python连接es之es更新操作示例详解
2022-11-21 06:11:48