NumPy(一)—— 数据类型、创建数组

Python模块——NumPy

NumPy(一)—— 数据类型及创建数组

大家可以关注 知乎或微信公众号的share16,我们也会同步更新此文章。

NumPy (Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。

NumPy 是一个运行速度非常快的数学库,主要用于数组计算,包含:

  • 功能强大的N维数组对象;
  • 精密广播功能函数;
  • 集成 C/C+和Fortran 代码的工具;
  • 强大的线性代数、傅立叶变换和随机数等功能;

一、数据类型及创建数组

1.1 常量

NumPy(一)—— 数据类型、创建数组

; 1.2 数据类型(np.dtype)

NumPy(一)—— 数据类型、创建数组
NumPy(一)—— 数据类型、创建数组

1.3 时间日期(datetime64)

在numpy中,将字符串转换成时间日期类型: np.datetime64(str)

  1. 从字符串创建 datetime64 类型时,默认情况下,numpy 会根据字符串自动选择对应的单位;
  2. 从字符串创建 datetime64 类型时,可以强制指定使用的单位;
  3. 从字符串创建 datetime64 类型时,如果单位不统一,则一律转化成其中最小的单位;
  4. 使用 arange() 创建 datetime64 数组,用于生成日期范围( arange():类似于range() );
'''
(1). 从字符串创建 datetime64 类型时,默认情况下,numpy 会根据字符串自动选择对应的单位
'''
import numpy as np
a = np.datetime64('2022-04-20')
print(a, type(a), a.dtype, sep=', ')

b = np.datetime64('2022-04-20 16:06:06')
print(b, type(b), b.dtype, sep=', ')

'''
(2). 从字符串创建 datetime64 类型时,可以强制指定使用的单位
'''
c = np.datetime64('2022-04-20 16:06:06', 'Y')
print(c, type(c), c.dtype, sep=', ')

d = np.datetime64('2022-04', 'D')
print(d, type(d), d.dtype, sep=', ')

'''
(3). 从字符串创建 datetime64 类型时,如果单位不统一,则一律转化成其中最小的单位
'''
e = np.array(['2020-03', '2020-03-08', '2020-03-08 20:00'], dtype = 'datetime64')
print(e, type(e), e.dtype, sep=', ')

f = np.array(['2020-03', '2020-03-08', '2020-03-08 20:00'], dtype = np.datetime64)
print(f, type(f), f.dtype, sep=', ')

e == f

'''
(4). 使用 arange() 创建 datetime64 数组,用于生成日期范围
arange():类似于range()
'''
a = np.arange('2022-04-01', '2022-04-20', dtype='datetime64')
print(a, type(a), a.dtype, sep='\n')

NumPy(一)—— 数据类型、创建数组

1.4 时间间隔(timedelta64)

timedelta64 表示两个 datetime64 之间的差。timedelta64 也是带单位的,并且和相减运算中的两个 datetime64 中的 较小的单位保持一致。

  1. 两个 datetime64 相减
  2. datetime64 加/减 timedelta64 (timedelta64的单位 要小于等于 datetime64的单位)
'''
(1).  两个 datetime64 相减
'''
import numpy as np
a = np.datetime64('2022-04-20') - np.datetime64('2022-04-02')
print(a, type(a), a.dtype,sep=', ')

b = np.datetime64('2022-04-20 20') - np.datetime64('2022-04-02 08:30')
print(b, type(b), b.dtype,sep=', ')

'''
(2).  datetime64 加/减 timedelta64  (timedelta64的单位 要小于等于 datetime64的单位)
'''
c = np.datetime64('2022-04-20') + np.timedelta64(2,'h')
print(c, type(c), c.dtype,sep=', ')

d = np.datetime64('2022-04-20') + np.timedelta64(2,'M')

timedelta64 的运算

import numpy as np
a = np.timedelta64(1, 'Y')
b = np.timedelta64(6, 'M')
c = np.timedelta64(1, 'W')
d = np.timedelta64(1, 'D')
e = np.timedelta64(10, 'D')
print(a, b, a + b, a - b, 2 * a, a / b, c / d, c % e, sep=',  ')

'''
生成 timedelta64时,要注意 年('Y')和月('M') 这两个单位,无法和其它单位进行运算(因为一年有几天?一个月有几个小时?这些都是不确定的)
'''

numpy.datetime64 与 datetime.datetime 相互转换

NumPy(一)—— 数据类型、创建数组
import numpy as np
import datetime
a = '2020-04-20 09:09:09'
b = np.datetime64(a)
c = b.astype(datetime.datetime)
d = np.datetime64(c, 's')

lst = [a, b, c, d]

for i in lst:
    try:
        print(i, type(i), i.dtype, sep=' ,  ')
    except:
        print(i, type(i), sep=' ,  ')

工作日

NumPy(一)—— 数据类型、创建数组
'''  '2022-04-15':星期五
     roll:默认raise,它只会引发异常
     a1:a的下一个工作日
     a2:输入的日期不是工作日,提示错误
'''
import numpy as np
a1 = np.busday_offset('2022-04-15', offsets = 1)
print(a1, sep=', ')

a2 = np.busday_offset('2022-04-16', offsets = 0)

'''  roll:forward(求 未来日期)/backward(求 过去日期) '''
import numpy as np

a = np.datetime64('2022-04-15')
b = np.datetime64('2022-04-16')

a1 = np.busday_offset(a, offsets = 0, roll='forward')
a2 = np.busday_offset(a, offsets = 0, roll='backward')
b1 = np.busday_offset(b, offsets = 0, roll='forward')
b2 = np.busday_offset(b, offsets = 0, roll='backward')
print(a1, a2, b1, b2, sep=', ')

'''    offsets != 0
 (1).  (同offsets=0) 根据roll规则,跳到当前日期向前或向后最近的工作日;若是工作日,则返回当前日期;反之,则返回最近工作日;
 (2).  在(1)的结果上,再加上 'offsets个工作日'
'''
a3 = np.busday_offset(a, offsets = 1, roll='forward')
a4 = np.busday_offset(a, offsets = 1, roll='backward')
b3 = np.busday_offset(b, offsets = 1, roll='forward')
b4 = np.busday_offset(b, offsets = 1, roll='backward')
print(a3, a4, b3, b4, sep=', ')

a = np.datetime64('2022-04-01')
b = np.datetime64('2022-04-16')
print(np.is_busday(a),np.is_busday(b))

np.busday_count(a,b)

1.5 创建数组(ndarray)

  1. 通过 array() 进行创建;
  2. 通过 asarray() 进行创建;
  3. 通过 fromfunction() 进行创建;
  4. 其他方法,如下图所示;
''' array、asarray、fromfunction '''
import numpy as np

def func(x,y):
    return x+y

x = [[1,2,3], [1,2,3]]
a = np.array(x)
b = np.arange(1,5)
c = np.asarray(x, dtype=float)
d = np.fromfunction(func, (4,3), dtype='float64')
e = np.fromfunction(lambda x,y : x+2*y, (1,2), dtype='int64')
print(x, type(x), sep=', ', end='\n\n')
print(a, type(a), a.dtype, a.shape, a.ndim, a.size, sep=', ', end='\n\n')
print(b, type(b), b.dtype, b.shape, b.ndim, b.size, sep=', ', end='\n\n')
print(c, type(c), c.dtype, c.shape, c.ndim, c.size, sep=', ', end='\n\n')
print(d, type(d), d.dtype, d.shape, d.ndim, d.size, sep=', ', end='\n\n')
print(e, type(e), e.dtype, e.shape, e.ndim, e.size, sep=', ', end='\n\n')

'''运行结果:
[[1, 2, 3], [1, 2, 3]],

[[1 2 3]
 [1 2 3]], , int64, (2, 3), 2, 6

[1 2 3 4], , int64, (4,), 1, 4

[[1. 2. 3.]
 [1. 2. 3.]], , float64, (2, 3), 2, 6

[[0. 1. 2.]
 [1. 2. 3.]
 [2. 3. 4.]
 [3. 4. 5.]], , float64, (4, 3), 2, 12

[[0 2]], , int64, (1, 2), 2, 2
'''

NumPy(一)—— 数据类型、创建数组
import numpy as np
a = np.arange(2,8)
b = np.linspace(0,100,num=5,endpoint=True,retstep=False)
c = np.logspace(0,4,num=4,base=2)
d = np.empty((4,4), dtype=int)
e = np.zeros((2,2))
f = np.ones((2,2))
g = np.eye(3,k=1)
h = np.identity(4)
i = np.diag(d)
j = np.full((3,2), round(np.pi,2))
k = np.full_like(j, [1,2], dtype=int)
print(a, b, c, d, e, f, g, h, i, j, k, sep='\n\n')

1.6 结构数组

结构数组:首先需要定义结构,然后利用 np.array() 来创建数组,其参数 dtype 为定义的结构。

  1. 利用 字典 来定义结构
  2. 利用 包含多个元组的列表 来定义结构
import numpy as np
personType = np.dtype( { 'names': ['name', 'age', 'weight'], 'formats': ['U30', 'i8', 'f8']} )
personType1 = np.dtype([('name', 'U30'), ('age', 'i8'), ('weight', 'f8')])

a = np.array([('Liming', 24, 63.9), ('Mike', 15, 67.), ('Jan', 34, 45.8)], dtype=personType)
b = np.array([('Liming', 24, 63.9), ('Mike', 15, 67.), ('Jan', 34, 45.8)], dtype=personType1)

print(a, b, sep=', ')
print(a[0], b[0], sep=', ')
print(a[-2:], b[-2:], sep=', ')
print(a['name'], b['name'], sep=', ')
print(a['age'], b['age'], sep=', ')
print(a['weight'], b['weight'], sep=', ')

1.7 数组的属性

NumPy(一)—— 数据类型、创建数组

; 1.8 小练习

1.8.1 以下表达式运行的结果分别是什么?


print('{0}的结果是:{1:^10}'.format(' 0.3 == 3 * 0.1 ', str(0.3 == 3 * 0.1)))

'''
 0 * np.nan 的结果是:   nan
 np.nan - np.nan 的结果是:   nan
 np.nan == np.nan 的结果是:  False
 np.inf > np.nan 的结果是:  False
 0.3 == 3 * 0.1 的结果是:  False
'''

1.8.2 创建一个长度为10并且除了第五个值为1的空向量

import numpy as np
a = np.zeros(10, dtype=int)
a[4] = 1
print(a)

1.8.3 创建随机数数组(np.random)

np.random.random([size]) :生成 [0,1) 之间的随机小数,可通过size设置维度

import numpy as np
a0 = np.random.random()
a1 = np.random.random(6)
a2 = np.random.random((3,2))
a3 = np.random.random((3,2,3))
print(a0, a1, a2, a3, sep='\n\n')

np.random.randint(low [,high,size,dtype]) :生成 [low,high) 的随机整数

import numpy as np
a0 = np.random.randint(10)
a1 = np.random.randint(10, size=2)
a2 = np.random.randint(10, 20, (3,2))
a3 = np.random.randint(10, 20, (2,2,3))
print(a0, a1, a2, a3, sep='\n\n')

np.random.randn(d0,d1, …, dn):从标准正态分布中,返回(d0d1…*dn)个样本值

import numpy as np
a0 = np.random.randn()
a1 = np.random.randn(2)
a2 = np.random.randn(2,3)
a3 = np.random.randn(2,2,3)
print(a0, a1, a2, a3, sep='\n\n')

此外, np.random还有更多函数,大家可自行查询。

1.8.4 创建一个二维数组,其中边界值为1,其余值为0

import numpy as np

''' 0变成1 '''
a = np.zeros((5,6), dtype=int)
print(a)
print('\n')
a[0] = 1
a[-1] = 1
a[:,0] = 1
a[:,-1] =1
print(a)

''' 1变成0 '''
b = np.ones((5,6), dtype=int)
b[1:-1,1:-1] = 0
print(b)

1.8.5 创建长度为10的数组,从5开始,连续的数字之间的步长为3

import numpy as np
start = 5
num = 10
step = 3
stop = start + step * num
a = np.arange(start, stop, step)
print(a)

1.8.6 将本地图像导入并将其转换为数组

import numpy as np
from PIL import Image

img1 = Image.open('test.jpg')
a = np.array(img1)
print(a.shape, a.dtype)

谢谢大家🌹

Original: https://blog.csdn.net/weixin_42330887/article/details/124296602
Author: share16
Title: NumPy(一)—— 数据类型、创建数组

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/759093/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球