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]])
"""
相关推荐
bst@微胖子35 分钟前
Python高级语法之selenium
开发语言·python·selenium
王小义笔记40 分钟前
Postman如何流畅使用DeepSeek
开发语言·测试工具·lua·postman·deepseek
查理零世2 小时前
【蓝桥杯集训·每日一题2025】 AcWing 6118. 蛋糕游戏 python
python·算法·蓝桥杯
魔尔助理顾问3 小时前
一个简洁高效的Flask用户管理示例
后端·python·flask
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-request请求对象与url传参
开发语言·python·flask·flask3
流星白龙5 小时前
【C++】36.C++IO流
开发语言·c++
诚信爱国敬业友善6 小时前
常见排序方法的总结归类
开发语言·python·算法
The god of big data6 小时前
深入探索 DeepSeek 在数据分析与可视化中的应用
ai·数据挖掘·数据分析
nbsaas-boot7 小时前
Go 自动升级依赖版本
开发语言·后端·golang
架构默片7 小时前
【JAVA工程师从0开始学AI】,第五步:Python类的“七十二变“——当Java的铠甲遇见Python的液态金属
java·开发语言·python