Numpy中创建数组的9种方式小结
本文总结了Numpy中创建数组的9种常用方式,包括empty、array、zeros/ones、arange、linspace、random.rand、random.randn、random.randint以及fromfunction。通过具体代码示例,详细解析了各方法的参数用法、数据类型推断及适用场景,帮助开发者高效构建不同需求的NumPy数组。
1、使用empty方法创建数组
该方法用于生成一个未初始化的数组,dtype参数可指定随机数的数据类型;若未显式指定,系统将随机选择一种类型来生成随机数。
import numpy as np
dt = np.numpy([2, 2], dtype=int)

2、使用array创建数组
通过array方法,可以基于Python列表构建数组。当不设置dtype参数时,系统会自动从列表内容中推断数据类型。
import numpy as np
dt = np.array([1, 2, 3, 4, 5])
print('数组:', dt)
print('数据类型:', dt.dtype)
dt = np.array([1, 2, 3, 4, 5], dtype='f8') # 64位浮点数
print('数组:', dt)
print('数据类型:', dt.dtype)

3、使用zeros/ones创建数组
调用zeros/ones方法可生成全为“0”或“1”的数组,常用于需要临时数组且元素位置、大小一致的场景。此时“0”或“1”仅作为占位符使用。
import numpy as np
dt = np.zeros([3, 5], dtype=int)
print('数组:', dt)
print('数据类型:', dt.dtype)
dt = np.ones([5, 3], dtype=float)
print('数组:', dt)
print('数据类型:', dt.dtype)

4、使用arange创建数组
利用arange方法,可以根据指定的数据范围来创建数组。
import numpy as np
dt = np.arange(10, 30, 5)
print('数组:', dt)
print('数据类型:', dt.dtype)

5、使用linspace创建数组
linspace方法基于指定范围构造数组,其中num参数定义了开始值与结束值之间需要生成的数值个数。
若设置retstep为True,则改变计算输出,返回一个包含生成数组和步差值的元组。
import numpy as np
dt = np.linspace(20, 30, num=5)
print('数组:', dt)
print('数据类型:', dt.dtype)
dt = np.linspace(20, 30, num=5, endpoint=False)
print('数组:', dt)
print('数据类型:', dt.dtype)
dt = np.linspace(20, 30, num=5, retstep=True)
print('元组:', dt)

6、使用numpy.random.rand创建数组
在许多业务场景中,手动创建的数组往往无法满足需求,因此需要生成随机数组。
import numpy as np
dt = np.random.rand(10)
print('数组:', dt)
print('数据类型:', dt.dtype)

7、使用numpy.random.randn创建数组
numpy.random.randn方法是生成随机数组的另一种途径,其特点是能够产生符合正态分布的随机数。
import numpy as np
dt = np.random.randn(3, 5)
print('数组:', dt)
print('数据类型:', dt.dtype)

8、使用numpy.random.randint创建数组
该方法可在10到30之间生成随机数,并从中选取5个数值来构建数组。
import numpy as np
dt = np.random.randint(10, 30, 5)
print('数组:', dt)
print('数据类型:', dt.dtype)

9、使用fromfunction创建数组
fromfunction方法允许通过函数规则来创建数组。其中shape参数用于制定创建数组的规则,当shape=(4,5)时,最终创建的结果即为4行5列的二维数组。
import numpy as np
dt = np.fromfunction(lambda i, j:i + j, (4, 5), dtype=int)
print('数组:', dt)
print('数据类型:', dt.dtype)

到此这篇关于Numpy中创建数组的9种方式小结的文章就介绍到这了,更多相关Numpy 创建数组内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













