【Python】【NumPy】学习笔记

【Python】【NumPy】学习笔记

索引

单维切片

与python中的切片一样,slice切片和中括号切片,不包括停止索引stop

  • slice(start,stop,step)
  • start:stop:step

多维切片

切片+逗号+冒号/省略号。

python多维数组不能用多维索引/逗号,但numpy可以:

python 复制代码
# x=[[1,2,3],[4,5,6],[7,8,9]]
# print(x[...,1]) # TypeError: list indices must be integers or slices, not tuple
x=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(x[...,1]) # [2 5 8]

省略号可以替换成冒号

整数索引

整数数组索引是指使用一个数组来访问另一个数组的元素:[第一维索引,第二维索引,第三维索引,...]

二维数组常见:[行索引,列索引]

python 复制代码
import numpy as np 
 
x = np.array([[1,  2],  [3,  4],  [5,  6]])
# 获取数组中 (0,0),(1,1) 和 (2,0) 位置处的元素。
y = x[[0,1,2],  [0,1,0]]
# 结果:[1  4  5]

x = np.array([[  0,  1,  2],[  3,  4,  5],[  6,  7,  8],[  9,  10,  11]]) 
# 取这个数组的四个角元素
rows = np.array([[0,0],[3,3]]) 
cols = np.array([[0,2],[0,2]]) 
y = x[rows,cols]
# 索引:(0,0),(0,2),(3,0),(3,2)
print(x)
print(y)
'''
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
[[ 0  2]
 [ 9 11]]
'''

a = np.array([[1,2,3], [4,5,6],[7,8,9]])
b = a[1:3, 1:3]
c = a[1:3,[0,2]]
d = a[...,1:]
print(b)
'''
[[5 6]
 [8 9]]
'''
print(c)
'''
[[4 6]
 [7 9]]
'''
print(d)
'''
[[2 3]
 [5 6]
 [8 9]]
'''

布尔索引

布尔索引通过布尔运算(如:比较运算符)来获取符合指定条件的元素的数组。

python 复制代码
x = np.array([[  0,  1,  2],[  3,  4,  5],[  6,  7,  8]])
print(x)
'''
[[0 1 2]
 [3 4 5]
 [6 7 8]]
'''
print(x[x>3])
'''
[4 5 6 7 8]
'''
"""
以下几种多条件写法都会报错:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
"""
print(x[3 < x < 7])
print(x[x > 3 and x < 7])
print(x[x > 3 & x < 7])
print(x[(x > 3) and (x < 7)])
"""
正确写法:
"""
print(x[(x > 3) & (x < 7)])	# [4 5 6]
print(x[(x < 2) | (x > 3) & (x < 7)])	# [0 1 4 5 6]

print(x[np.logical_and(x > 3, x < 7)])
print(x[np.logical_or(x < 2, np.logical_and(x > 3, x < 7))])


a = np.array([np.nan,  1,2,np.nan,3,4,5])
print (a)
'''
[nan  1.  2. nan  3.  4.  5.]
'''
# 用 ~(取补运算符)过滤 NaN
print (a[~np.isnan(a)])
'''
[1. 2. 3. 4. 5.]
'''

a = np.array([1, 2 + 6j, 5, 3.5 + 5j])
print(a)
'''
[1. +0.j 2. +6.j 5. +0.j 3.5+5.j]
'''
# 过滤掉非复数元素
print(a[np.iscomplex(a)])
'''
[2. +6.j 3.5+5.j]
'''
相关推荐
AI探索者10 分钟前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者12 分钟前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽3 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时6 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿9 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python