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)
相关推荐
keyipatience28 分钟前
线程栈与TLS和线程互斥
java·linux·服务器·开发语言·ubuntu
我的xiaodoujiao33 分钟前
快速学习Python基础知识详细图文教程9--函数进阶
开发语言·python·学习·测试工具
weixin_408099671 小时前
2026 图片去水印 API 接口完全指南:一键去除图片水印(附 Python/Java/PHP/C# 示例)
java·python·php·图片处理·api调用·图片去水印·石榴智能
爱喝水的鱼丶1 小时前
SAP-ABAP:ALV通用封装实践——搭建可复用的ALV开发工具类,减少80%重复代码
开发语言·性能优化·sap·abap·erp·alv
去码头整点薯条ing1 小时前
某当网登录滑块【协议+OCR】
爬虫·python·ocr
脱胎换骨-军哥2 小时前
C++/Rust无缝互操作:混合系统新常态
开发语言·c++·rust
songroom2 小时前
Kimi K3:Rust封装XTP接口详细教程实践
开发语言·后端·rust
kebeiovo2 小时前
游戏服务端开发:Actor模型详解(Go语言)
开发语言·后端·golang
赶紧写完去睡觉2 小时前
Anaconda 创建虚拟环境与使用
python·pycharm·conda
迷途呀2 小时前
Python:函数中的参数类型
开发语言·笔记·python·langchain·nlp