python数据分析库

python数据分析库之Numpy笔记

  1. 导入numpy模块
python 复制代码
import numpy as np
  1. 通过列表创建一个数组
python 复制代码
arr = np.array([1,2,3,4,5])
# 输出 array([1, 2, 3, 4, 5])
  1. 使用type函数查看数组对象类型
python 复制代码
type(arr) 
# 输出 <class 'numpy.ndarray'> 
  1. 使用dtype属性查看数组元素的数据类型
python 复制代码
arr.dtype
# 输出 dtype('int64')
  1. 通过二维列表创建一个二维数组
python 复制代码
arr2 = np.array([[1,2,3], [4,5,6]])
# 输出 array([[1, 2, 3],[4, 5, 6]])
  1. 使用ndim属性查看数组的维度
python 复制代码
arr2.ndim 
# 输出 2
  1. 使用shape属性查看数组的形状
python 复制代码
arr2.shape
# 输出 (2, 3)
  1. 使用zeros方法创建一个元素全0的数组
python 复制代码
# 1. 创建一维数组
np.zeros(4)
# 输出 array([0., 0., 0., 0.])

# 2.创建二维数组
np.zeros((2,4))
# 输出 array([[0., 0., 0., 0.], [0., 0., 0., 0.]])
  1. 使用empty方法创建没有具体值的数组
python 复制代码
# 创建一个不为0的三维数组,趋近于0,但不为0
np.empty((2,2,2))
# 输出 
"""
array([[[0.00000000e+000, 0.00000000e+000],
        [0.00000000e+000, 0.00000000e+000]],

       [[0.00000000e+000, 1.81816158e-321],
        [6.35681408e+151, 1.33473535e-311]]])
"""
  1. 使用arange方法创建序列数组
python 复制代码
np.arange(6)
# 输出 array([0, 1, 2, 3, 4, 5])
  1. 使用eye方法创建单位矩阵
python 复制代码
# 创建一个4*4的单位矩阵,斜对角是1和0
np.eye(4) 
# 输出 
"""
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])
"""
  1. 使用ones方法创建元素全是1的数组
python 复制代码
np.ones((2,2))
# 输出
"""
array([[1., 1.],
       [1., 1.]])
"""
  1. 创建指定数据类型的数组
python 复制代码
arr3 = np.array([1,2,3],dtype=np.float64) # 指定数据类型为float的数组
arr4 = np.array([1,2,3],dtype=np.int32) # 指定数据类型为int的数组
arr4 = np.array(['a', 'b', 'c'],dtype=np.string_) # 指定数据类型为string的数组
  1. 使用astype方法转换数组的数据类型
python 复制代码
int_arr5 = np.array([1,2,3], dtype=np.int32)
float_arr5 = int_arr5.astype(np.float64)
  1. 高精度类型向低精度类型转换,取整数部分
python 复制代码
float_arr = np.array([1.2, 2.3, 3.4, 4.0])
int_arr = float_arr.astype(np.int32)
# 输出 array([1, 2, 3, 4], dtype=int32)
  1. 使用reshape方法转换数组维度
python 复制代码
arr = np.arange(10).reshape((2,5))
# 输出
"""
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
"""
  1. 使用T属性将数组转置
python 复制代码
arr.T
# 输出
"""
array([[0, 5],
       [1, 6],
       [2, 7],
       [3, 8],
       [4, 9]])
"""
相关推荐
zone77394 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant4 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来5 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_5 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend6 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽6 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python