Python 数据分析库NumPy

NumPy是Python中用于科学计算(数据分析)的第三方库,主要来处理 数值型 的多维度数组与矩阵运算,也针对数组运算提供大量的数学函数库。
1、数组的创建
import random
import numpy as np

# 使用numpy生成数组,得到ndarray的类型
t1 = np.array([1, 2, 3])
print(t1)  # [1 2 3]
print(type(t1))  # 
print('- ' * 20)

t2 = np.array(range(10))
print(t2)  # [0 1 2 3 4 5 6 7 8 9]
print('- ' * 20)

t3 = np.arange(10)  # 和t2一样
print(t3)  # [0 1 2 3 4 5 6 7 8 9]
print('- ' * 20)

t4 = np.arange(4, 10, 2)  # 可以传入步长
print(t4)  # [4 6 8]
print(t4.dtype)  # int32(ndarray类型包含dtype属性,可以查询数组内部数据的类型)
print('- ' * 20)

t5 = np.array(range(1, 4), dtype=float)  # ndarray类型的数组内部数据类型,可以通过传入dtype参数进行指定
print(t5)  # [1. 2. 3.]
print(t5.dtype)  # float64
print('- ' * 20)

t6 = np.array(range(11, 14), dtype='float32')  # dtype参数还可以传入字符串进行指定
print(t6)  # [11. 12. 13.]
print(t6.dtype)  # float32
print('- ' * 20)

t7 = np.array([1, 1, 0, 0, 1], dtype=bool)  # 指定bool类型
print(t7)  # [ True  True False False  True]
print(t7.dtype)  # bool
print('- ' * 20)

t8 = t7.astype('int8')  # 调整数据类型
print(t8)  # [1 1 0 0 1]
print(t8.dtype)  # int8
print('- ' * 20)

t9 = np.array([random.random() for i in range(10)])  # numpy中的小数
print(t9)  # [0.17992435 0.21145029 0.43916962 0.17318445 0.14025875 0.71023035  0.64834252 0.3996  0.1263777  0.04871356]
print(t9.dtype)  # float64
print('- ' * 20)

t10 = np.round(t9, 2)  # 将数据取2位小数(可以直接处理一个列表,python自带的round只能处理一个数据)
print(t10)  # [0.18 0.21 0.44 0.17 0.14 0.71 0.65 0.4  0.13 0.05]


t11 = np.zeros((3, 4))  # 创建一个全为0的数组
print(t11)
# [[0. 0. 0. 0.]
#  [0. 0. 0. 0.]
#  [0. 0. 0. 0.]]
print('***')

t22 = np.ones((3, 4))  # 创建一个全为1的数组
print(t22)
# [[1. 1. 1. 1.]
#  [1. 1. 1. 1.]
#  [1. 1. 1. 1.]]
print('***')

t33 = np.eye(3)  # 创建一个对角线为1的正方形数组(方阵)
print(t33)
# [[1. 0. 0.]
#  [0. 1. 0.]
#  [0. 0. 1.]]
print('***')

t44 = np.arange(12).reshape((3, 4))
print(t44)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
print('***')

print(np.argmax(t44, axis=0))  # 寻找行上最大值的索引(8 9 10 11 索引位置都是2)
# [2 2 2 2]
print(np.argmin(t44, axis=1))  # 寻找列上最小值的索引(0 4 8 索引位置都是0)
# [0 0 0]
print('*** ' * 20)

# -------------------------------------------------------
# numpy生成随机数

t55 = np.random.randint(10, 20, (4, 5))  # 生成4行5列的数组,数据是从10到20的随机数
print(t55)
# [[12 15 12 19 14]
#  [18 10 11 17 13]
#  [18 10 10 11 15]
#  [12 10 13 15 14]]
 
 

你可能感兴趣的:(Python知识汇总,python)