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)
相关推荐
我不管我就要叫小猪几秒前
C/C++----命名空间
c语言·开发语言·c++
min(a,b)11 分钟前
学习第 6 天:类型注解、装饰器与高级特性
python·学习
自由随风飘26 分钟前
JAVA中的面向对象-3
java·开发语言
码云骑士33 分钟前
80-指令微调Instruction-Tuning-指令数据构造-多任务训练-过拟合检测
python
小羊先生car1 小时前
RTOS-F429-HAL-(动/静态)任务的创建(2026/7/27)
开发语言·算法·c#
爱昏羔1 小时前
上篇:从PDF到向量库 — 物流行业RAG系统的知识库构建全解析
python·langchain·pdf·agent·rag
麻雀飞吧1 小时前
最新量化实现难点,规则和流程要先有形状
人工智能·python
用户0332126663671 小时前
使用 Python 在 Word 文档中添加或删除文本框
python
LONGZETECH1 小时前
新能源汽车动力系统仿真硬核拆解:五系统分层架构的设计逻辑与技术权衡
c语言·开发语言·架构·汽车·汽车仿真教学软件·汽车教学软件
醉城夜风~2 小时前
C++模板详解:从基础到高级全面解析
java·开发语言·c++