numpy初体验

# -*- coding:utf-8 -*-
import numpy as np
import random

# ############数值型的数组#############

# 创建数组
t1 = np.array([1, 2, 3])
print(t1)  # [1 2 3]
print(type(t1))  # 

t2 = np.arange(4.1, 5.6, 0.2)
print(t2)  # [4.1 4.3 4.5 4.7 4.9 5.1 5.3 5.5]
print(t1.dtype)  # int32
print(t2.dtype)  # float64

# numpy指定数据类型
t3 = np.arange(10, dtype="int")
print(t3)  # [0 1 2 3 4 5 6 7 8 9]
t4 = np.array([1, 1, 0, 0, 1], dtype="bool")
print(t4)  # [ True  True False False  True]
t5 = t4.astype("int")
print(t5)  # [1 1 0 0 1]

# numpy小数
t6 = np.array([random.random() for i in range(5)])
print(t6)
print(t6.dtype)  # float64

# 保留两位小数,四舍五入
t7 = np.round(t6, 2)
print(t7)
# 一维数组,返回元组,第一个值表示数组个数
print(t7.shape)  # (5,)
# 二维数组,返回元组,第一个是行,第二个列
t8 = np.array([[1, 2, 3], [4, 5, 6]])
print(t8)
print(t8.shape)  # (2, 3)

# 修改数组形状,类似行列转换
t9 = t8.reshape((3, 2))
print(t9)
print(t9.shape)  # (3, 2)

# 二维数组转成一维数组
t10 = t8.flatten()  #
print(t10)  # [1 2 3 4 5 6]
print(t10.shape)  # (6,)

# 利用reshape构造三维数组
t11 = np.arange(24).reshape((2, 3, 4))
print(t11)
print(t11.shape)  # (2, 3, 4)

# 随机生成一个取值范围在大等于10到小于50之间的三行四列二维数组
t12 = np.random.randint(10, 50, (3, 4))
print(t12)

 

你可能感兴趣的:(python,numpy,python,numpy,数组)