在NumPy中创建空数组/矩阵的方法
作者:帮酷 时间:2023-11-02 05:30:35
如何在NumPy中创建空数组/矩阵?
在添加行的情况下,你最好的选择是创建一个与数据集最终一样大的数组,然后向它添加数据 row-by-row:
>>> import numpy
>>> a = numpy.zeros(shape=(5,2))
>>> a
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
>>> a[0] = [1,2]
>>> a[1] = [2,3]
>>> a
array([[ 1., 2.],
[ 2., 3.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
NumPy数组与列表是一个非常不同的数据结构,它被设计用于不同的方式。 你对 hstack的使用可能非常低效。 每次调用它时,现有数组中的所有数据都将复制到新数组中。 (append 函数会有同样的问题。) 如果你想一次构建一个矩阵,最好把它放在一个列表中,直到它完成,然后将它转换成数组。
mylist = []
for item in data:
mylist.append(item)
mat = numpy.array(mylist)
item 可以是列表,数组或者任何 iterable,只要每个 item 具有相同数量的元素。
在这种特殊情况下,你可以简单地使用( data 是一些保存矩阵列的iterable )
mat = numpy.array(data)
(也请注意,使用 list 作为变量名可能不是好做法,因为它通过该名称屏蔽内置类型,这可能导致 Bug 。)
来源:https://blog.csdn.net/dowemo/article/details/78412851
标签:numpy,空数组,矩阵
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
jsp include文件时的一个乱码解决方法
2024-03-27 19:34:28
自动备份mssql server数据库并压缩的批处理脚本
2024-01-24 00:30:11
javascript中的toFixed固定小数位数 简单实例分享
2024-05-21 10:20:28
![](https://img.aspxhome.com/file/2023/8/124878_0s.jpg)
Python如何实现爬取B站视频
2021-10-09 07:46:04
![](https://img.aspxhome.com/file/2023/7/112997_0s.jpg)
Python 多线程爬取案例
2022-11-17 16:02:06
![](https://img.aspxhome.com/file/2023/6/90546_0s.png)
css学习笔记:表格隔行点击变色
2009-04-30 13:15:00
![](https://img.aspxhome.com/file/UploadPic/20094/30/11f49f89ed8g215-25s.jpg)
JavaScript 颜色梯度和渐变效果
2009-03-18 11:16:00
![](https://img.aspxhome.com/file/UploadPic/20093/18/ColorGrads-46s.gif)
VS Code有哪些奇技淫巧(必知)
2022-01-07 21:10:47
![](https://img.aspxhome.com/file/2023/7/100847_0s.png)
python 将大文件切分为多个小文件的实例
2021-05-23 23:32:02
简单谈谈Python中函数的可变参数
2022-05-13 02:32:49
Python制作CSDN免积分下载器
2021-12-25 03:46:35
![](https://img.aspxhome.com/file/2023/5/71385_0s.jpg)
MySql 备忘录
2024-01-22 12:56:48
通过代码实例了解Python3编程技巧
2023-07-13 17:48:46
网站508规范(译)
2008-04-03 13:26:00
![](https://img.aspxhome.com/file/UploadPic/20084/3/gobuttons_85s.jpg)
分类与类型的问题
2008-09-12 13:10:00
![](https://img.aspxhome.com/file/UploadPic/20089/12/2008912131610841s.jpg)
对python中的xlsxwriter库简单分析
2022-08-22 22:46:01
Python运算符重载用法实例分析
2023-03-18 07:28:11
python实现三子棋游戏
2021-11-20 04:10:37
![](https://img.aspxhome.com/file/2023/0/133350_0s.png)
CSS盒模型
2009-06-09 14:23:00
![](https://img.aspxhome.com/file/UploadPic/20096/9/01-91s.png)
Python练习之操作SQLite数据库
2024-01-22 03:23:39
![](https://img.aspxhome.com/file/2023/1/79611_0s.png)