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]])
"""
相关推荐
databook1 天前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机2 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i2 天前
django中的FBV 和 CBV
python·django
c8i2 天前
python中的闭包和装饰器
python
这里有鱼汤2 天前
小白必看:QMT里的miniQMT入门教程
后端·python