Python笔记:详解使用Python列表创建ndarray

本文详细介绍了NumPy库中的数组创建、术语解释、数据类型管理、文件操作及实例应用,旨在帮助开发者掌握NumPy数组的核心概念与实践技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入

import numpy as np

在此引入一次,下面直接使用 np

简单的创建

x = np.array([1, 2, 3, 4, 5])
print('x = ', x) # x = [1 2 3 4 5]

一些实用的术语

  • 一维数组称之为秩为 1 的数组, N 维数组的秩为 N
  • 数组的形状是指每个维度的大小。例如,秩为 2 的数组的形状对应于数组的行数和列数.

ndarray中的 .shape 属性

x = np.array([1, 2, 3, 4, 5])
print('x has dimensions:', x.shape) # x has dimensions: (5,)
print(type(x)) # class 'numpy.ndarray'
print('The elements in x are of type:', x.dtype) # The elements in x are of type: int64

说明:

  • shape 属性返回了元组 (5,),告诉我们 x 的秩为 1(即 x 只有一个维度),并且有 5 个元素。
  • type() 函数告诉我们 x 的确是 NumPy ndarray
  • 最后,.dtype 属性告诉我们 x 的元素作为有符号 64 位整数存储在内存中。

关于ndarray的数据类型

  • 与 Python 列表不同的是,ndarray 的所有元素都必须类型相同。
  • 如果向 np.array() 函数提供同时具有整数和字符串的 Python 列表,NumPy 会将所有元素解析为字符串。
    x = np.array([1, 2, 'World'])
    print('The elements in x are of type:', x.dtype) # The elements in x are of type: U21
    

创建秩为 2 的 ndarray

Y = np.array([[1,2,3],[4,5,6],[7,8,9], [10,11,12]])
print('Y has dimensions:', Y.shape) # Y has dimensions: (4, 3)
print('Y has a total of', Y.size, 'elements') # Y has a total of 12 elements Y is an object of type: class 'numpy.ndarray'
print('The elements in Y are of type:', Y.dtype) # The elements in Y are of type: int64
  • .shape 属性返回元组 (4,3),告诉我们 Y 的秩为 2,有 4 行 3 列。
  • .size 属性告诉我们 Y 共有 12 个元素。

创建具有浮点数和整数的 ndarray

x = np.array([1,2,3])
y = np.array([1.0,2.0,3.0])
z = np.array([1, 2.5, 4])

print(x.dtype) # int64
print(y.dtype) # float64
print(z.dtype) # float64

说明:

  • 当我们创建同时包含浮点数和整数的 ndarray 时,NumPy 也会为其元素分配 float64 dtype。这叫做向上转型。
  • 因为 ndarray 的所有元素都必须类型相同,因此在这种情况下,NumPy 将 z 中的整数向上转型为浮点数,避免在进行数学计算时丢失精度。

创建指定 dtype 的 ndarray

x = np.array([1.5, 2.2, 3.7, 4.0, 5.9], dtype = np.int64)
print()
print('x = ', x) # x = [1 2 3 4 5]
print()
print('The elements in x are of type:', x.dtype) # The elements in x are of type: int64

  • NumPy 通过去除小数将浮点数转换成了整数。
  • 如果希望达到一定的计算精度来节省内存,则指定 ndarray 的数据类型很有用。

在NumPy中加载文件和读取文件

x = np.array([1, 2, 3, 4, 5])
# 将 x ndarray 保存到叫做 my_array.npy 的文件中
np.save('my_array', x) 
# 使用 load() 函数将保存的 ndarray 加载到变量中
y = np.load('my_array.npy')
print()
print('y = ', y) # y = [1 2 3 4 5]
print()
print('y is an object of type:', type(y)) # y is an object of type: class 'numpy.ndarray' 
print()
print('The elements in y are of type:', y.dtype) # The elements in y are of type: int64

注意:

  • 从文件中加载数组时,确保包含文件名和扩展名 .npy,否则将出错。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值