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)
相关推荐
互联网杂货铺6 分钟前
完美搭建appium自动化环境
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
Gyoku Mint25 分钟前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
fpcc34 分钟前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗1 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长1 小时前
Python 构建法律DeepSeek RAG
开发语言·python
luojiaao1 小时前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
终焉代码1 小时前
STL解析——list的使用
开发语言·c++
SoFlu软件机器人1 小时前
智能生成完整 Java 后端架构,告别手动编写 ControllerServiceDao
java·开发语言·架构
英英_1 小时前
视频爬虫的Python库
开发语言·python·音视频
猛犸MAMMOTH2 小时前
Python打卡第46天
开发语言·python·机器学习