数据分析(三)之numpy数组学习

数据分析学习线路图

在这里插入图片描述

1、什么是numpy?

一个在Python中做科学计算的基础库,重在数值计算,也是大部分PYTHON科学计算库的基础库,多用于在大型、多维数组上执行数值运算

1.1 numpy常用的数据类型

在这里插入图片描述

数据类型的操作

在这里插入图片描述

1.2 使用numpy创建数组

import numpy as np
import random

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

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

t3 = np.arange(4, 10, 2)  # [4 6 8] 从4-10 步长为2
print(t3)
print(type(t3))  # int32

print(t3.dtype)
print("*" * 100)
# numpy中的数据类型

t4 = np.array(range(1, 4), dtype="i1")  # [1 2 3]
print(t4)
print(t4.dtype)    # int8

# numpy中的bool类型
t5 = np.array([1, 1, 0, 1, 0, 0], dtype=bool)  # [ True  True False  True False False]
print(t5)
print(t5.dtype)   # bool

# 调整数据类型
t6 = t5.astype("int8")   # [1 1 0 1 0 0]
print(t6)
print(t6.dtype)   # int8

# numpy中的小数
t7 = np.array([random.random() for i in range(10)])
print(t7)    # [0.15925535 0.68749422 0.87527896 0.81028664 0.70966472 ... 0.5344896 ]
print(t7.dtype)   # float64

# 修改浮点数的小数位置
t8 = np.round(t7, 2)  # [0.16 0.69 0.88 0.81 0.71 0.21 0.01 0.51 0.33 0.53]
print(t8)

打印输出:
[1 2 3]
<class 'numpy.ndarray'>
[0 1 2 3 4 5 6 7 8 9]
<class 'numpy.ndarray'>
[4 6 8]
<class 'numpy.ndarray'>
int32
[1 2 3]
int8
[ True  True False  True False False]
bool
[1 1 0 1 0 0]
int8
[0.15925535 0.68749422 0.87527896 0.81028664 0.70966472 0.21499349 0.01478751 0.50647445 0.3335658  0.5344896 ]
float64
[0.16 0.69 0.88 0.81 0.71 0.21 0.01 0.51 0.33 0.53]

1.3 数组的形状

在这里插入图片描述
解答: reshape(3,4)表示的是返回一个3行4列的数组,即返回值是一个3行4列的数,但对a的本身形状并没有做出改变

在这里插入图片描述
c = c.reshape((b.shape[0]*b.shape[1],)) 同样返回一个一位数组,0,1表示b的行和列

1.4 数组和数的计算

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
同样如果c是一个2行1列的数组时,则按照列进行运算。

1.4 基本概念

在这里插入图片描述

解答:(3,3,3)和(3,2)无法进行计算,而 (3,3,2)和(3,2)则可以进行计算
原因:(3,3,2)三维数组可以理解为3块(3,2)的二维数组,与第二个(3,2)对应,所以后者可以进行计算

请看代码

import numpy as np

a_temp = np.array(range(18))
a = a_temp.reshape(3, 3, 2)

print(a)
print("*****************************************************************************************")
b = ([[1, 2], [3, 4], [5, 6]])

print(a+b)

输出的结果:
[[[ 0  1]
 [ 2  3]
 [ 4  5]]

 [[ 6  7]
 [ 8  9]
  [10 11]]

 [[12 13]
  [14 15]
  [16 17]]]
  ******************************************************************************************
[[[ 1  3]
  [ 5  7]
  [ 9 11]]

 [[ 7  9]
  [11 13]
  [15 17]]

 [[13 15]
  [17 19]
 [21 23]]]
 
Process finished with exit code 0

轴的概念

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

第二天学习小结【思维导图】

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40926887/article/details/111088624