【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]
'''
相关推荐
hhhjhl4 小时前
flutter_for_openharmony逆向思维训练app实战+学习日历实现
学习·flutter
我的xiaodoujiao4 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 44--将自动化测试结果自动推送至钉钉工作群聊
前端·python·测试工具·ui·pytest
沈浩(种子思维作者)4 小时前
铁的居里点(770度就不被磁铁吸了)道理是什么?能不能精确计算出来?
人工智能·python·flask·量子计算
yufuu985 小时前
使用Scikit-learn进行机器学习模型评估
jvm·数据库·python
近津薪荼5 小时前
优选算法——双指针8(单调性)
数据结构·c++·学习·算法
计算机毕业编程指导师5 小时前
大数据可视化毕设:Hadoop+Spark交通分析系统从零到上线 毕业设计 选题推荐 毕设选题 数据分析 机器学习 数据挖掘
大数据·hadoop·python·计算机·spark·毕业设计·城市交通
计算机毕业编程指导师5 小时前
【计算机毕设选题】基于Spark的车辆排放分析:2026年热门大数据项目 毕业设计 选题推荐 毕设选题 数据分析 机器学习 数据挖掘
大数据·hadoop·python·计算机·spark·毕业设计·车辆排放
浔川python社5 小时前
浔川社团关于产品数据情况的官方通告
python
生活很暖很治愈5 小时前
GUI自动化测试[3]——控件&数鼠标操作
windows·python·功能测试·测试工具
老蒋每日coding5 小时前
Python3基础练习题详解,从入门到熟练的 50 个实例(一)
开发语言·python