day 018 numpy

numpy模块

作用

用来做数据分析,对numpy数组(既有行又有列)--矩阵进行科学运算

import numpy as np#约定俗成的
arr1=np.array([1,2,3])
arr2=np.array([4,5,6])
print(arr1*arr2)#[ 4 10 18]

创建numpy数组--》可变

一维数组(不再讨论范围内)

arr=np.array([1,2,4])
print(type(arr),arr)#<class 'numpy.ndarray'> [1 2 4]

二维数组

arr=np.array([
    [1,2,3],
    [4,5,6]
])
print(arr)
#[[1 2 3]
# [4 5 6]]

三维数组(不再讨论范围内)-->tensorflow

arr=np.array([
    [
        [1,2,3],
        [4,5,6]
    ],
    [
        [7,8,9],
        [1,2,3]
    ]
])
print(arr)
'''
[[[1 2 3]
  [4 5 6]]

 [[7 8 9]
  [1 2 3]]]
'''

numpy数组的属性

T 数组的转置(对高维数组而言)--》行列互换,转置

arr=np.array([
    [1,2,3],
    [4,5,6]
])
print(arr,'
',arr.T)'''
[[1 2 3]
 [4 5 6]] 
 [[1 4]
 [2 5]
 [3 6]]'''

dtype 数组元素的数据类型,numpy数组是属于python解释器;

print(arr.dtype)#int32

size 数组元素的个数

print(arr.size)#6

ndim 数组的维数

print(arr.ndim)#2

shape 数组的维度大小(以元组形式)

print(arr.shape)#(2, 3)
print(arr.shape[0])#2
print(arr.shape[1])#3

类型转换

arr =arr.astype( np.float64)
print(arr)'''
[[1. 2. 3.]
 [4. 5. 6.]]'''

切片numpy数组

print(arr[:,:])#行,列
'''[[1 2 3]
 [4 5 6]]'''
print(arr[0,0])'''1'''
print(arr[0,:])'''[1 2 3]'''
print(arr[:,-2:])'''[[2 3]
 [5 6]]'''

逻辑取值

print(arr[arr>4])#[5 6]

赋值

arr[0,0]=0
print(arr)
'''[[0 2 3]
 [4 5 6]]'''
arr[0,:]=0
print(arr)
'''[[0 0 0]
 [4 5 6]]'''
arr[:,:]=0
print(arr)
'''[[0 0 0]
 [0 0 0]]'''

数组的合并

arr1=np.array([
    [1,2,3],
    [4,5,6]
])
arr2=np.array([
    [7,8,9],
    ['a','b','c']
])
print(np.hstack((arr1,arr2)))#只能放元组
print(np.vstack((arr1,arr2)))
print(np.concatenate((arr1,arr2),axis=1))
print(np.concatenate((arr1,arr2),axis=0))
'''[['1' '2' '3' '7' '8' '9']
 ['4' '5' '6' 'a' 'b' 'c']]
[['1' '2' '3']
 ['4' '5' '6']
 ['7' '8' '9']
 ['a' 'b' 'c']]
[['1' '2' '3' '7' '8' '9']
 ['4' '5' '6' 'a' 'b' 'c']]
[['1' '2' '3']
 ['4' '5' '6']
 ['7' '8' '9']
 ['a' 'b' 'c']]'''

通过函数创建numpy数组

print(np.ones((2,3)))
'''[[1. 1. 1.]
 [1. 1. 1.]]'''
print(np.zeros((2,3)))
'''[[0. 0. 0.]
 [0. 0. 0.]]'''
print(np.eye(3,3))
'''[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]'''
print(np.linspace(1,100,10))
#[  1.  12.  23.  34.  45.  56.  67.  78.  89. 100.]
print(np.arange(2,10))
#[2 3 4 5 6 7 8 9]
arr1=np.zeros((1,12))
print(arr1.reshape((3,4)))
'''[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]'''

numpy数组运算

# +-*/
arr=np.ones((3,4))*4
print(arr)
'''[[4. 4. 4. 4.]
 [4. 4. 4. 4.]
 [4. 4. 4. 4.]]'''

numpy数组运算函数

print(np.sin(arr))
'''[[-0.7568025 -0.7568025 -0.7568025 -0.7568025]
 [-0.7568025 -0.7568025 -0.7568025 -0.7568025]
 [-0.7568025 -0.7568025 -0.7568025 -0.7568025]]'''

矩阵运算--点乘

arr1 = np.array([
    [1, 2, 3],
    [4, 5, 6]
])
arr2 = np.array([
    [1, 2],
    [4, 5],
    [6, 7]
])
#2*3  3*2
print(np.dot(arr1,arr2))
'''[[27 33]
 [60 75]]'''

求逆

arr = np.array([[1, 2, 3], [4, 5, 6], [9, 8, 9]])
print(np.linalg.inv(arr))
'''[[ 0.5        -1.          0.5       ]
 [-3.          3.         -1.        ]
 [ 2.16666667 -1.66666667  0.5       ]]'''

numpy数组数学和统计方法

print(np.sum(arr[0,:]))#6

numpy.random.rand生成随机数

print(np.random.rand(3,4))#正态分布
'''[[0.34072936 0.04588527 0.16372231 0.96185426]
 [0.51459343 0.17003796 0.30000238 0.23489212]
 [0.81754459 0.53810634 0.24564255 0.03756553]]'''
print(np.random.random((3,4)))
'''[[0.29967839 0.00167616 0.91552593 0.47693086]
 [0.69258731 0.27441853 0.28070978 0.54993094]
 [0.16784168 0.71806167 0.77576507 0.20575752]]'''
s=np.random.RandomState(1)
print(s.random((3,4))
'''[[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01]
 [1.46755891e-01 9.23385948e-02 1.86260211e-01 3.45560727e-01]
 [3.96767474e-01 5.38816734e-01 4.19194514e-01 6.85219500e-01]]''' 
arr = np.array([[1, 2, 3], [4, 5, 6], [9, 8, 9]])
np.random.shuffle(arr)
print(arr)    
'''[[9 8 9]
 [1 2 3]
 [4 5 6]]'''
print(np.random.choice([1,2,3],1))#[1]     
print(np.random.randint(1,100,(3,4)))
'''[[41  1 97 88]
 [95 27 48 66]
 [14 80 91 98]]'''

matplolib模块

作用

画图

条形图

from matplotlib import pyplot as plt#约定俗成
from matplotlib.font_manager import FontProperties# 修改字体

font=FontProperties(fname='C:WindowsFontssimsun.ttc')

plt.style.use('ggplot')#设置背景

clas=['3班','4班','5班','6班']
students=[50,55,45,60]
clas_index=range(len(clas))

plt.bar(clas_index,students,color='darkblue')# x轴  y轴  背景

plt.xlabel('学生',fontproperties=font)
plt.ylabel('学生人数',fontproperties=font)
plt.title('班级—学生人数',fontproperties=font,fontsize=20,fontweight=25)
plt.xticks(clas_index,clas,fontproperties=font)#clas替换clas_index
plt.show()

直方图

import numpy as np
from matplotlib import pyplot as plt#约定俗成
from matplotlib.font_manager import FontProperties#修改字体
font= FontProperties(fname='C:WindowsFontssimsun.ttc')

plt.style.use('ggplot')#设置背景

x1=np.random.rand(10000)
x2=np.random.rand(10000)

fig=plt.figure()#生成一张画布
ax1=fig.add_subplot(1,2,1)#1行2列第一个
ax2=fig.add_subplot(1,2,2)#1行2列第二个

ax1.hist(x1,bins=50,color='darkblue')# bins=50表示每个变量的值分成50份,即会有50根柱子
ax2.hist(x2,bins=50,color='y')

fig.suptitle('两个正太分布',fontproperties=font,fontsize=20)
ax1.set_title('x1的正太分布',fontproperties=font)
ax2.set_title('x2的正太分布',fontproperties=font)
plt.show()

折线图

import numpy as np
from matplotlib import pyplot as plt#约定俗成
from matplotlib.font_manager import FontProperties#修改字体
font= FontProperties(fname='C:WindowsFontssimsun.ttc')

plt.style.use('ggplot')

np.random.seed(10)
x1=np.random.rand(40).cumsum()
x2=np.random.rand(40).cumsum()
x3=np.random.rand(40).cumsum()
x4=np.random.rand(40).cumsum()

plt.plot(x1,color='r',linestyle='-',marker='o',label='红圆线')
plt.plot(x2,color='y',linestyle='--',marker='*',label='黄虚线')
plt.plot(x3,color='b',linestyle='-',marker='s',label='蓝方线')
plt.plot(x4,color='black',linestyle=':',marker='s',label='黑方线')
plt.legend(loc='best',prop=font)#显示label
plt.show()

散点图+直线图

import numpy as np
from matplotlib import pyplot as plt#约定俗成
from matplotlib.font_manager import FontProperties#修改字体
font= FontProperties(fname='C:WindowsFontssimsun.ttc')

plt.style.use('ggplot')

fig=plt.figure()
ax1=fig.add_subplot(1,2,1)
ax2=fig.add_subplot(1,2,2)

x=np.arange(20)
y=x**2

x2=np.arange(20)
y2=x2

ax1.scatter(x,y,c='r',label='红')
ax2.scatter(x2,y2,c='b',label='蓝')

ax1.plot(x,y)
ax2.plot(x2,y2)

fig.suptitle('两张图',fontproperties=font,fontsize=15)
ax1.set_title('散点图',fontproperties=font)
ax2.set_title('折线图',fontproperties=font)
ax1.legend(prop=font)
plt.show()

pandas模块

作用

操作excel/json/sql/ini/csv(配置文件)

pd从excel中读取DataFrame数据类型

import numpy as np
import pandas as pd

np.random.seed(10)
index=pd.date_range('2019-01-01',periods=6,freq='M')
print(index)
columns=['c1','c2','c3','c4']
print(columns)
val=np.random.rand(6,4)
print(val)

df=pd.DataFrame(index=index,columns=columns,data=val)
print(df)

保存文件,读出文件

df.to_excel('date_cc.xlsx')

df=pd.read_excel('date_cc.xlsx',index_col=[0])
print(df)

print(df.index)
print(df.columns)
print(df.values)
print(df[['c1','c2']])

按照Index取值

print(df.loc['2019-01-31'])
print(df.loc['2019-01-31':'2019-05-31'])

按照values取值

print(df)
print(df.iloc[0,0])
df.iloc[0,:]=0
print(df)
原文地址:https://www.cnblogs.com/zqfzqf/p/11632364.html