数据处理利器--numpy(一)

110 阅读1分钟

环境准备 pip install numpy==1.19.5

numpy 是 python 生态中功能最强大的数学库,虽然是 python 生态的库, 但是核心代码都是 c/c++/fortran 实现的, numpy为什么这么快可以参考, numpy 主要是提供具有矢量运算和复杂广播能力的 ndarray 数组,以及基于 ndarray 之上的 ufunc (universal function) 函数。


# (导入 numpy) 一般都会将 numpy 重命名为 np
import numpy as np 

my_array = np.array([1, 2, 3, 4, 5]) 

print(my_array)

我们可以根据不同的场景使用不同的函数生成 ndarray 对象

  1. array
  2. asarray
  3. arange
  4. ones, ones_like
  5. zeros, zeros_like
  6. empty, empty_like 7.full, full_like
  7. eye, identity
  8. linespace 等函数生成不同的 ndarray

7178691-78ab11f67e7077a6.png

numpy 支持的类型也很多, 包括内置的

7178691-2f2d7406a8bc076c.png

7178691-5cc31115615737b7.png

还支持自定义类型


# numpy 自定义 dtype 练习
import numpy as np

# 自定义 dtype 
scoretype = np.dtype({
    'names': ['name', 'chinese', 'english', 'math'],
    'formats': ['S32', 'i', 'i', 'i'],
})
peoples = np.array(
    [
        ("zhangfei", 66, 65, 30),
        ("guanyu", 95, 85, 98),
        ("zhaoyun", 93, 92, 96),
        ("huangzhong", 90, 88, 77),
        ("dianwei", 80, 90, 90)
        # 通过 dtype 参数指定类型
    ], dtype=scoretype)
print(peoples)
print(peoples[['name', 'chinese']])
print(peoples.dtype)

# 或者 
import numpy as np

# 定义一个自定义的 dtype
my_dtype = np.dtype([
    ('name', 'S10'),
    ('age', 'i4'),
    ('weight', 'f8')
])

# 定义一个包含三个元素的数组
person = np.array([('Alice', 25, 60.0), ('Bob', 30, 75.5), ('Charlie', 35, 80.0)],
                  dtype=my_dtype)

# 输出数组及其数据类型
print(person)