numpy note.md

本文详细介绍NumPy库的基础知识,涵盖ndarray数据结构的创建方法,如使用array、arange、linspace函数,以及zeros、ones、eye等特殊用途数组的创建。深入探讨数组属性、自定义数据类型、索引与切片操作,并展示数组的数学运算和基本方法。

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

numpy基础

import numpy as np

ndarray是numpy中基本的数据结构,创建array的方法一般有如下几种

a = np.array([1,2,3,4])
print(a)
[1 2 3 4]
a = np.arange(1,10)
print(a)
[1 2 3 4 5 6 7 8 9]
a = np.arange(0,12).reshape(3,4)
print(a)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

也可以用一些其他的函数来创建有特殊用途的array

linspace可以等间距取出规定数量的值,其中也包括小数。endpoint参数规定是否取到最后一位

a = np.linspace(0,1,10,endpoint=False)
print(a)
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
a = np.linspace(0,1,10,
                endpoint = True)
print(a)
[0.         0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
 0.66666667 0.77777778 0.88888889 1.        ]
a = np.zeros((3,4))
print(a)
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
a = np.ones((3,4),dtype = int)
print(a)
[[1 1 1 1]
 [1 1 1 1]
 [1 1 1 1]]

eye方法创建一个n阶方阵

a = np.eye(3)
print(a)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

array数组也有自身的属性

a = np.arange(20).reshape(2,2,5)
print(a)
[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]]

 [[10 11 12 13 14]
  [15 16 17 18 19]]]

dtype属性代表array中数据的类型,可以是int,float,str等

a.dtype
dtype('int32')

dtype属性的修改不可以直接进行,而应该借助于astype()方法

a.dtype = "float64"
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-18-a4cdf5bd3aee> in <module>()
----> 1 a.dtype = "float64"


ValueError: When changing to a larger dtype, its size must be a divisor of the total size in bytes of the last axis of the array.
a = a.astype(np.float64)
print(a)
print(a.dtype)
[[[ 0.  1.  2.  3.  4.]
  [ 5.  6.  7.  8.  9.]]

 [[10. 11. 12. 13. 14.]
  [15. 16. 17. 18. 19.]]]
float64

在array比较复杂时,也可以自定义数据类型

stu_dtype = np.dtype([("id",int),("name",str,10),("成绩",int)])
a = np.array([(1,"samson",98),(2,"Johnson",95),(3,"Nicole",97)],dtype = stu_dtype)
a
array([(1, 'samson', 98), (2, 'Johnson', 95), (3, 'Nicole', 97)],
      dtype=[('id', '<i4'), ('name', '<U10'), ('成绩', '<i4')])

数组的索引和切片操作

一维数组下的操作,和python的列表切片是一致的

a = np.arange(10)
print(a)
[0 1 2 3 4 5 6 7 8 9]
a[0]
0
a[1:5]
array([1, 2, 3, 4])
a[:]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a[1:8:2]
array([1, 3, 5, 7])
a[::-1]
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

多维数组下的操作

a = np.arange(30).reshape(3,2,5)
a
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9]],

       [[10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29]]])
a[0]
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

如果索引中括号中加入一个tuple,(或者不加圆括号),就代表在“纵深”方向上进行索引查找。第一个数字代表第一维检索,第二个数字代表第二维

a[(0,1)]
array([5, 6, 7, 8, 9])
a[(0,1,3)]
8
a[0,:,1:4]
array([[1, 2, 3],
       [6, 7, 8]])

如果索引中括号中加入一个list,就代表在“水平”方向上进行索引查找

a[[0,1]]
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9]],

       [[10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]]])
a[0][[0,1]]
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
a[[0,1]][0]
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

数组的数学操作和基本方法

a = np.arange(1,11)
a
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
b = np.arange(10)
b
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a+b
array([ 1,  3,  5,  7,  9, 11, 13, 15, 17, 19])
a*b
array([ 0,  2,  6, 12, 20, 30, 42, 56, 72, 90])
np.sin(a)
array([ 0.84147098,  0.90929743,  0.14112001, -0.7568025 , -0.95892427,
       -0.2794155 ,  0.6569866 ,  0.98935825,  0.41211849, -0.54402111])
a.mean()
5.5
a.sum()
55
C:\Users\lenovo>pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple/ Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple/ Collecting numpy Using cached https://pypi.tuna.tsinghua.edu.cn/packages/2e/19/d7c972dfe90a353dbd3efbbe1d14a5951de80c99c9dc1b93cd998d51dc0f/numpy-2.3.1.tar.gz (20.4 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... error error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [13 lines of output] + D:\python\python.exe C:\Users\lenovo\AppData\Local\Temp\pip-install-tpg8twj9\numpy_831df4d9ff554f88a6269112c87b56f2\vendored-meson\meson\meson.py setup C:\Users\lenovo\AppData\Local\Temp\pip-install-tpg8twj9\numpy_831df4d9ff554f88a6269112c87b56f2 C:\Users\lenovo\AppData\Local\Temp\pip-install-tpg8twj9\numpy_831df4d9ff554f88a6269112c87b56f2\.mesonpy-xirytnhb -Dbuildtype=release -Db_ndebug=if-release -Db_vscrt=md --native-file=C:\Users\lenovo\AppData\Local\Temp\pip-install-tpg8twj9\numpy_831df4d9ff554f88a6269112c87b56f2\.mesonpy-xirytnhb\meson-python-native-file.ini The Meson build system Version: 1.6.1 Source dir: C:\Users\lenovo\AppData\Local\Temp\pip-install-tpg8twj9\numpy_831df4d9ff554f88a6269112c87b56f2 Build dir: C:\Users\lenovo\AppData\Local\Temp\pip-install-tpg8twj9\numpy_831df4d9ff554f88a6269112c87b56f2\.mesonpy-xirytnhb Build type: native build Project name: NumPy Project version: 2.3.1 Activating VS 17.14.7 ..\meson.build:1:0: ERROR: Compiler cl cannot compile programs. A full log can be found at C:\Users\lenovo\AppData\Local\Temp\pip-install-tpg8twj9\numpy_831df4d9ff554f88a6269112c87b56f2\.mesonpy-xirytnhb\meson-logs\meson-log.txt [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. [notice] A new release of pip is available: 24.2 -> 25.1.1 [notice] To update, run: python.exe -m pip install --upgrade pip error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details.
最新发布
06-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值