1. Matplotlib data visualization-environment construction

1. Installation

Windows, Linux, Mac can be used. Install numpy and matplotlib two packages (how to install Baidu).

Verify that the installation is successful:

Enter the following code, a straight line will come out

import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[-4,-3,-2,-1])
plt.show()

2. Introduction to numpy

numpy is an open source numerical calculation extension of python, which can be used to store and process large matrices, which is more efficient than python's own data structure. numpy turns python into a free and powerful MATLAB system.

(1) Create

There are generally three ways to create:

1. Convert from python's basic data object

2. Generated by numpy endogenous function

3. Read data from the hard disk (file)

import numpy as np 
#1、从python的基础数据对象转化
a=[1,2,3,4]
x1=np.array(a)

#2、通过numpy内生函数生成
x2=np.arange(11)

#3、从硬盘(文件)读取数据
#文件名,文件分隔符,跳过第几行,使用那几列
x=np.loadtxt('1.csv',delimiter=',',skiprows=1,usecols=(1,4,6),unpack=False)
#将几列数据分别放到不同的变量中,unpack设置为true
a,b,c=np.loadtxt('1.csv',delimiter=',',skiprows=1,usecols=(1,4,6),unpack=True)

(2) Commonly used functions in numpy

#生成一个长度为10的取值为1到100之间的变量
c=np.random.randint(1,100,10)
#用numpy库调用
np.min(c)#最小值
np.max(c)#最大值
np.mean(c)#平均值
np.average#平均值,可指定权重
#用对象调用
c.min(c)#最小值
c.max(c)#最大值
c.mean(c)#平均值
c.average#平均值,可指定权重

Note: When using the sort method, np.sort(x) is to generate a sorted new sequence. The original sequence will not be changed. Using x.sort() is to sort the original sequence and will not generate a new sequence.

Three, homework

1. Use numpy to generate random arrays within 100

2. Store the array to a file, and then read the array from the file

3. Sort the array and find the maximum, minimum, mean, and variance

import numpy as np
#使用numpy生成100以内的随机数组
arr1=np.random.randint(1,100,50)
#将数组存储到文件
np.savetxt('arr.csv',arr1,fmt='%d',delimiter=',')
#从该文件读取数组
arr2=np.loadtxt('arr.csv',dtype=int,delimiter=',')
#对数组进行排序,求最大值、最小值、均值、方差
print('最大值{0},最小值{1},均值{2},方差{3}'
.format(np.max(arr2),np.min(arr2),np.mean(arr2),np.var(arr2)))

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_40836442/article/details/112322877