python numpy库使用

1、np.where()

np.where 函数是三元表达式 x if condition else y 的向量化版本,它有两种用法:

  • np.where(condition,x,y) 当where内有三个参数时,第一个参数表示条件,当条件成立时where方法返回x,当条件不成立时where返回y;
  • np.where(condition) 当where内只有一个参数时,那个参数表示条件,当条件成立时,where返回的是每个符合condition条件元素的坐标,返回的是以元组的形式;

2、ndarray.astype()

astype()方法可对数组的元素类型进行转换;

复制代码
import numpy as np
 
a = np.array([1,2,3])
b = a.astype(np.float)
c = a.astype(np.complex)
 
print(b.dtype)
print(b)
 
print(c.dtype)
print(c)

float64
[1. 2. 3.]
complex128
[1.+0.j 2.+0.j 3.+0.j]

3、ndarray.dtype

ndarray.dtype可以得到数组元素的类型;

复制代码
import numpy as np 
a = np.array([1,2,3])
print(a.dtype)

输出结果:
int32

4、ndarray.reshape()

ndarray.reshape()可以改变数组形状;

复制代码
import numpy as np
 
a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
print(a)
 
b = a.reshape(2,6)
print(b)


[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
[[ 1  2  3  4  5  6]
 [ 7  8  9 10 11 12]]

5、ndarray.shape()

ndarray.shape获得数组的形状,返回元祖(几行,几列) ;

复制代码
import numpy as np
 
a = np.array([1,2,3])
b = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
 
print(a.shape)
print(b.shape)

输出:
(3,)
(3, 4)
相关推荐
满栀5857 小时前
原生JS + ECharts 多图表可视化实战:从业务实现到工程化优化
开发语言·javascript·echarts
Ming_studying7 小时前
Python + SQLite FTS5 构建本地文档全文搜索器:增量索引、中文检索与高亮
jvm·数据库·python·sqlite
玉鸯7 小时前
让 Agent 面向用户:AG-UI 协议构建 Agent 前端
前端·python·agent
熬夜苦读学习7 小时前
Qt-- 系统相关
开发语言·qt
弹简特7 小时前
【Java项目-企悦抽】11-用户与认证模块-实现用户登录03(结束登录功能)-完成测试+对接前端+登录拦截器
java·开发语言
小白学大数据7 小时前
把 Modbus 轮询塞进 Trio 的异步循环:内存映射与定时采集实战
网络·python·搜索引擎
haolin123.7 小时前
类和对象(下)
c语言·开发语言·c++
FriendshipT8 小时前
Ubuntu 20.04 下使用 Ollama 本地部署 AI 大模型
linux·人工智能·python·深度学习·ubuntu
天天爱吃肉82188 小时前
# 商用车多体动力学实战笔记|第7篇:制动系统与制动热衰退、ABS滞环控制
大数据·人工智能·笔记·python·嵌入式硬件·汽车
bamb008 小时前
一个项目带你入门AI应用开发08
python