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)
相关推荐
我是人机不吃鸭梨1 分钟前
Flutter AI 集成革命(2025版):从 Gemini 模型到智能表单验证器的终极方案
开发语言·javascript·人工智能·flutter·microsoft·架构
沐知全栈开发1 分钟前
服务定位器模式
开发语言
计算机徐师兄2 分钟前
Python基于Django的网络入侵检测系统(附源码,文档说明)
python·django·网络入侵检测·网络入侵检测系统·python网络入侵检测系统·网络入侵·python网络入侵检测
期待のcode5 分钟前
Java Object 类
java·开发语言
Wang's Blog11 分钟前
Lua: 协程编程详解之从基础到多任务处理与应用实战
开发语言·lua
大连好光景14 分钟前
socket.socket模块--网络通信
网络·python·网络协议
笙枫16 分钟前
LangGraph Agent 架构基础:从概念到第一个可运行的Agent
开发语言·架构·php
csbysj202034 分钟前
DOM 验证
开发语言
codists34 分钟前
《Grokking Concurrency》读后感
python
superman超哥44 分钟前
Rust 表达式与语句的区别:函数式思维与控制流设计
开发语言·后端·rust·rust表达式·rust语句·函数式思维·控制流设计