Python数据分析与展示:科学计算基础库numpy

numpy 科学计算基础库
官方文档:https://docs.scipy.org/doc/numpy/user/quickstart.html

列表和数组区别

列表:数据类型可以不同
数组:数据类型相同

N维数组对象 ndarray

dimension 维度: 一组数据的组织形式
轴axis 数据维度
秩rank 轴的数量
ndarray数组一般要求所有元素类型相同(同质),数组下标从0开始

ndarray元素类型

布尔:bool(True False)
c语言int,环境有关: intc,intp
整数:int8,int16,int32,init64
无符号整数: uint8,uint16,uint32,uinit64
半精度浮点数:float16,float32,float64
复数:complex64,complex128(实部+j虚部)

python语法支持:整数,浮点数,复数

ndarray对象的属性

ndim 秩: 行向量或列向量的极大无关组中包含向量的个数
shape 尺寸n行m列
size  元素个数 n*m
dtype 元素类型
itemsize 每个元素大小

ndarray数组创建

1、通过列表、元组创建
    array(list/tuple)

2、numpy函数创建
    arange(n) 0 ~ n-1
    ones(shape) 全1数组
    zeros(shape) 全0数组
    full(shape, val) 全val数组
    eye(n) n*n数组,对角线为1, 其余为0
    ones_like(a) 根据a的形状,全1数组
    zeros_like(a) 根据a的形状,全0数组
    full_like(a, val) 根据a的形状,全val数组
    linspase()  根据起止数据等间距填充数据
    concatenate() 合并数组

ndarray数组变换

维度变换
    reshape(shape) 不改变原数组,返回新数组
    resize(shape)  改变原数组
    swapaxes(ax1, ax2) 维度调换
    flatten() 降维,折叠为一维数组

类型变换
    astype(type) 返回新数组
    tolist() ndarray数组转为列表

ndarray数组操作

索引, 切片 和python列表类似
维度之间用逗号(,),切片用冒号(:)

ndarray数组运算

numpy一元函数,元素级运算

    np.abs(x) np.fabs(x) 各元素绝对值 
    np.sqrt(x) 各元素平方根
    np.square(x) 各元素平方
    np.log(x) np.log10(x) np.log2(x) 各元素自然对数,10底对数,2底对数
    np.ceil(x)  np.floor(x) 各元素的取整值ceil向上, floor向下
    np.rint(x)  各元素四舍五入值
    np.modf(x)  各元素小数和整数部分拆为两个数组
    np.cos(x) np.sin(x) np.tan(x)普通型三角函数
    np.cosh(x) np.sinh(x)  np.tanh(x) 双曲型三角函数
    np.exp(x)  各元素指数值
    np.sign(x) 各元素符号值(1(+), 0, -1(-))

numpy二元函数

    + - * / **  两个数组计算
    np.maximum(x, y) np.fmax() 元素级的最大值
    np.minimum(x, y) np.fmin() 元素级的最小值
    np.mod(x, y) 元素级的模运算
    np.copysign(x, y) 将y元素符号赋值给x元素
    > < >= <= == != 比较运算 

代码示例

# -*- coding: utf-8 -*-

# @File    : numpy_demo.py
# @Date    : 2018-05-06

import numpy as np

# ndarray对象的属性
def foo1():
    a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
    print(a)
    """
    [[1 2 3 4]
     [5 6 7 8]]
    """

    # 秩
    print(a.ndim) # 2

    # 尺寸 n行m列
    print(a.shape) # (2, 4)

    # 元素个数 n*m
    print(a.size) # 8

    # 元素类型
    print(a.dtype) # int64

    # 每个元素大小
    print(a.itemsize) # 8


# 通过列表或元组创建ndarray对象
def foo2():
    # 从列表创建
    a = np.array([1, 2, 3])
    print(type(a))
    # <class 'numpy.ndarray'>

    # 从元组创建
    b = np.array((1, 2, 3))
    print(type(b))
    # <class 'numpy.ndarray'>

    # 列表元组混合创建
    c = np.array([[1, 2, 3], (1, 2, 3)])
    print(type(c))
    print(c)
    """
    <class 'numpy.ndarray'>
    [[1 2 3]
     [1 2 3]]
    """

# 通过numpy函数创建ndarray对象
def foo3():
    # 指定范围
    a = np.arange(10)
    print(a)
    # [0 1 2 3 4 5 6 7 8 9]

    # 全1数组
    b = np.ones((3, 4), dtype=np.int32)
    print(b)
    """
    [[1 1 1 1]
     [1 1 1 1]
     [1 1 1 1]]
    """

    # 全0数组
    c = np.zeros((3, 4), dtype=np.int32)
    print(c)
    """
    [[0 0 0 0]
     [0 0 0 0]
     [0 0 0 0]]
    """

    # n*n数组,对角线为1, 其余为0
    d = np.eye(5, dtype=np.int32)
    print(d)
    """
    [[1 0 0 0 0]
     [0 1 0 0 0]
     [0 0 1 0 0]
     [0 0 0 1 0]
     [0 0 0 0 1]]
    """
    # 全值数组
    e = np.full((3, 4), 5)
    print(e)
    """
    [[5 5 5 5]
     [5 5 5 5]
     [5 5 5 5]]
    """

    # 根据起止数据等间距填充数据
    f = np.linspace(1, 10, 4, dtype=np.int32)
    print(f)
    # [ 1  4  7 10]

    # 合并数组
    g = np.array([1, 2, 3], dtype=np.int32)
    h = np.array([4, 5, 6], dtype=np.int32)
    j = np.concatenate((g, h))
    print(j)
    # [1 2 3 4 5 6]


# ndarray数组变换
def foo4():
    a = np.ones((3, 4), dtype=np.int)
    print(a)
    """
    [[1 1 1 1]
     [1 1 1 1]
     [1 1 1 1]]
    """
    print(a.ndim)  # 2

    # 不改变原数组,返回新数组
    b = a.reshape((2, 6))
    print(b)
    """
    [[1 1 1 1 1 1]
     [1 1 1 1 1 1]]
    """

    # 改变原数组
    a.resize((6, 2))
    print(a)
    """
    [[1 1]
     [1 1]
     [1 1]
     [1 1]
     [1 1]
     [1 1]]
    """

    # 降维,折叠为一维数组
    c = a.flatten()
    print(c)
    # [1 1 1 1 1 1 1 1 1 1 1 1]

    # 修改类型
    d = c.astype(np.float)
    print(d)
    # [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

    # 转为列表
    e = c.tolist()
    print(e)
    # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]


# 一维数组,索引和切片
def foo5():
    a = np.array([1, 2, 3, 4, 5])
    print(a[3])
    # 4

    print(a[1: 4: 1])
    # [2 3 4]

# 多维数组, 索引和切片
def foo6():
    a = np.arange(24).reshape(2, 3, 4)
    print(a)
    """
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]
    """
    print(a[0, 2, 3])  # 11
    print(a[-1, -2, -3])  # 17

    print(a[:, :, ::2])
    """
    [[[ 0  2]
      [ 4  6]
      [ 8 10]]

     [[12 14]
      [16 18]
      [20 22]]]
    """

# 数组与标量之间的运算
def foo7():
    a = np.arange(24).reshape((2, 3, 4))
    print(a)
    """
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]
    """
    # 计算平均值
    print(a.mean())
    # 11.5

    s = a/a.mean()
    print(s)
    """
    [[[0.         0.08695652 0.17391304 0.26086957]
      [0.34782609 0.43478261 0.52173913 0.60869565]
      [0.69565217 0.7826087  0.86956522 0.95652174]]

     [[1.04347826 1.13043478 1.2173913  1.30434783]
      [1.39130435 1.47826087 1.56521739 1.65217391]
      [1.73913043 1.82608696 1.91304348 2.        ]]]
    """

# numpy一元函数
def foo8():
    a = np.arange(24).reshape((2, 3, 4))
    print(a)
    """
    [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]
    """

    # 求平方
    b =  np.square(a)
    print(b)
    """
    [[[  0   1   4   9]
      [ 16  25  36  49]
      [ 64  81 100 121]]

     [[144 169 196 225]
      [256 289 324 361]
      [400 441 484 529]]]
    """


    # 开方
    c = np.sqrt(a)
    print(c)
    """
    [[[0.         1.         1.41421356 1.73205081]
      [2.         2.23606798 2.44948974 2.64575131]
      [2.82842712 3.         3.16227766 3.31662479]]

     [[3.46410162 3.60555128 3.74165739 3.87298335]
      [4.         4.12310563 4.24264069 4.35889894]
      [4.47213595 4.58257569 4.69041576 4.79583152]]]
    """

    # 分离整数和小数
    d = np.modf(c)
    print(d)
    """

    (array([[[0.        , 0.        , 0.41421356, 0.73205081],
            [0.        , 0.23606798, 0.44948974, 0.64575131],
            [0.82842712, 0.        , 0.16227766, 0.31662479]],

           [[0.46410162, 0.60555128, 0.74165739, 0.87298335],
            [0.        , 0.12310563, 0.24264069, 0.35889894],
            [0.47213595, 0.58257569, 0.69041576, 0.79583152]]]), 
    array([[[0., 1., 1., 1.],
            [2., 2., 2., 2.],
            [2., 3., 3., 3.]],

           [[3., 3., 3., 3.],
            [4., 4., 4., 4.],
            [4., 4., 4., 4.]]]))
    """

# numpy二元函数
def foo9():重点内容
    a = np.array([1, 4, 5, 8])
    b = np.array([2, 3, 6, 7])

    # 求最大值
    c = np.maximum(a, b)
    print(c)
    # [2 4 6 8]

    # 比较运算
    d = a > b
    print(d)
    # [False  True False  True]

猜你喜欢

转载自blog.csdn.net/mouday/article/details/80216113