有幸参加了DataWhale举办的Numpy组队学习。收获颇多。
每天记录一些自己之前的知识盲点,需经常温习。
一、数据类型
1、常见数据类型
2、时间日期和时间增量
在 numpy 中,我们很方便的将字符串转换成时间日期类型 datetime64 ( datetime 已被 python 包含的日期时间库所占用)。 datatime64 是带单位的日期时间类型,其单位如下:
二、数组创建
数组创建的方法颇多,现一一道来。
前提条件:import numpy as np
1、通过array()函数进行创建
import numpy as np # 创建一维数组 a = np.array([0, 1, 2, 3, 4]) b = np.array((0, 1, 2, 3, 4)) print(a, type(a)) # [0 1 2 3 4] <class 'numpy.ndarray'> print(b, type(b)) # [0 1 2 3 4] <class 'numpy.ndarray'> # 创建二维数组 c = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) print(c, type(c)) # [[11 12 13 14 15] # [16 17 18 19 20] # [21 22 23 24 25] # [26 27 28 29 30] # [31 32 33 34 35]] <class 'numpy.ndarray'> # 创建三维数组 d = np.array([[(1.5, 2, 3), (4, 5, 6)], [(3, 2, 1), (4, 5, 6)]]) print(d, type(d)) # [[[1.5 2. 3. ] # [4. 5. 6. ]] # # [[3. 2. 1. ] # [4. 5. 6. ]]] <class 'numpy.ndarray'>2、通过asarray()函数进行创建
array() 和asarray() 都可以将结构数据转化为 ndarray,但是array() 和asarray() 主要区别就是当数据源是ndarray 时, array() 仍然会 copy 出一个副本,占用新的内存,但不改变 dtype 时 asarray() 不会。
def asarray(a, dtype=None, order=None): return array(a, dtype, copy=False, order=order) import numpy as np x = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] y = np.array(x) z = np.asarray(x) x[1][2] = 2 print(x,type(x)) # [[1, 1, 1], [1, 1, 2], [1, 1, 1]] <class 'list'> print(y,type(y)) # [[1 1 1] # [1 1 1] # [1 1 1]] <class 'numpy.ndarray'> print(z,type(z)) # [[1 1 1] # [1 1 1] # [1 1 1]] <class 'numpy.ndarray'>3、通过fromfunction()函数进行创建
def fromfunction(function, 1 shape, **kwargs): 【例】通过在每个坐标上执行一个函数来构造数组。 import numpy as np def f(x, y): return 10 * x + y x = np.fromfunction(f, (5, 4), dtype=int) print(x) # [[ 0 1 2 3] # [10 11 12 13] # [20 21 22 23] # [30 31 32 33] # [40 41 42 43]] x = np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int) print(x) # [[ True False False] # [False True False] # [False False True]] x = np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int) print(x) # [[0 1 2] # [1 2 3] # [2 3 4]]