Python 基础(五)

原文链接:http://www.one2know.cn/python5/

  • pandas缺失值处理
import pandas as pd
importrandom
df01 = pd.DataFrame(np.random.randint(1,9),size = (4,4))
print(df01)
df01.ix[1:2,1:2] = np.NaN #从0开始算的第1,2行的第1,2列赋为空值
print(df01)

print(df01.dropna()) #只要包含NaN的数据行都删掉
print(df01.dropna(axis = 1)) #只要包含NaN的数据列都删掉
print(df01.dropna(how = 'all')) #必须全是NaN的数据行才删除

print(df01.fillna(0)) #将所有NaN变成0
print(df01.fillna({0:1,1:4,2:3,3:8})) #将每列的NaN指定变成不同的数
  • pandas常用数学统计方法(默认都按列)
    count(): 非NaN数据的个数
    sum(): 默认按列求和 sum(axis = 1)按行求和
    min()/max(): 最大最小值
    quantile(0.25): 计算样本分数位(0到1),参数默认0.5,即中位数
    median(): 中位数
    cumsum(): 累加和
    pct_change(): 计算百分数的变化
    std(): 标准差
    var(): 方差
    describe(): 得到以上一堆方法及各列结果的表
  • 相关数据与协方差
df01 = pd.DataFrame({'year':[1,2,3,4],'money':[40,50,60,70]})
df01.cov() #协方差: 正数正相关,负数负相关
df01.corr() #相关数 : -1到1之间

ser01 = pd.Series(['a','b','c','d','a','b','c'])
ser01.value_counts() #统计数
ser01[ser01.isin(['b','c'])] #分别判断是否在列表当中,相当于过滤,成员资格
ser01.unique() #去重
  • pandas层次索引
    swaplevel交换内外层索引
  • matplotlib绘图库
import matplotlib.pyplot as plt
import numpy as np

plt.plot([1,2,7],[3,5,2]) #绘制 折线图
plt.show() #显示图片

#显示情况
%matplotlib tk #在GUI中显示
%matplotlib inline #在行内显示

#figure
x = np.arange(-3,3,0.1)
y1 = np.sin(x)
y2 = np.cos(x)

plt.figure(num = 5,figsize = (8,5)) #创建第一个图形,figsize单位为100像素
plt.plot(x,y1)
plt.plot(x,y2)
plt.show() #两条曲线在一个图里显示

#也可以
plt.plot(x,y1,x,y2)
plt.show()

plt.plot([2,3,4,5],color = 'red',linestyle = 'dashed',marker = 'o',alpha = 0.5) 
#一维数组为y值,index为x值(从0开始)
#颜色也可以同RGB格式,即'#FF0000'
#dashed参数表示虚线,虚线也可以用'--'表示,还有'-.'也可以用
#marker 的 'o'参数表示用圆点标记点
#alpha表示透明度
#具体各种style可查看帮助 help(plt.plot)

#简写方式
plt.plot(x,y1,'ro--')

'''
    刻度,标题,标签,图例
'''
x1 = [1,2,3]
y1 = [5,7,4]
x2 = [1,2,3]
y2 = [10,12,14]

#解决中文显示问题
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ["SimHei"]
mpl.rcParams['axes.unicode_minus'] = False

plt.figure()
plt.plot(x1,y1,'ro-',label = '红实线) 
plt.plot(x2,y2,'bo--',label = '蓝虚线') 

#设置标题标签
plt.xlabel('月份')
plt.xlabel('美元/亿')
plt.xlabel('月份')
plt.title('进出口数据')

#设置范围
plt.xlim(0,6)
plt.ylim(0,15)

#设置刻度
plt.xticks([1,2,3,4,5,6],str(i)+'月' for i in range(1,7))
plt.yticks(np.arange(2,16,2),['200','300','400','500','600','700','800'])

#设置坐标轴信息
ax = plt.gca()
#设置边框
ax.spines['top'].set_color(none)
ax.spines['right'].set_color(none)

#生成默认图例
plt.legend() 

plt.show()
  • subplot子图:subplot(numRows,numCols,plotNum)
import matplotlib.pyplot as plt
import numpy as np

x1 = [1,2,3]
y1 = [5,7,4]
x2 = [1,2,3]
y2 = [10,12,14]

plt.figure() #创建图像
plt.subplot(221) #创建第1个子图,2行2列的第1个位置
plt.plot(x1,y1,'ro--')
plt.subplot(223) #创建第2个子图,2行2列的第3个位置
plt.plot(x2,y2,'bo-')

plt.show()

#面向对象的形式
x1 = [1,2,3]
y1 = [5,7,4]
x2 = [1,2,3]
y2 = [10,12,14]

fig = plt.figure() #创建图像(实例化对象)
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(212)

#在ax123上画图
ax1.plot(np.random.randn(50).cumsum(),'g--')
ax2.plot(np.random.randn(50).cumsum(),'b--')
ax3.plot(np.random.randn(50).cumsum(),'r--')

plt.show()
  • subplots子图
import matplotlib.pyplot as plt

fig,axes = plt.subplots(2,2) 
#也可以fig,axes = plt.subplots(nrows = 2,ncols = 2,sharex = True,sharey = True)
'''
    print(axes) #输出: 由图片object构成的 2x2的列表
'''
#axes是一个列表
axes[0].plot(range(10),'ro-')
axes[1].plot(range(10),'bo-')
axes[2].plot(range(10),'yo-')
axes[3].plot(range(10),'mo-')

plt.show()
  • 柱状图hist代替plot
  • numpy以矩阵为基础的数学计算模块
import numpy as np

#创建数组 help(array)
np.array([1,2,3]) #用一维列表创建
np.array((1,2,3)) #用元组创建
np.array([
        [
            [1,2,3],
            [4,5,6]
        ],
        [
            [3,4,6],
            [8,6,4]
        ]  
]) #多维数组
np.zeros((3,3)) #创建元素为0的数组,用元组(3,3)表示3行3列
np.zeros((2,3,3)) #三维0数组
np.ones((3,3)) #创建元素为1的数组
np.empty((3,3)) #初始化一个空矩阵
np.arange(1,9,2) #一维数组
np.linspace(1,10,5) #生成等差数列
np.logspace(0,2,5,base = 10) #生成等比数列,从1(10**0)到100(10**2)生成5个数,base默认为10
np.random.random((3,3)) #0到1的随机数二维数组
np.random.randn((3,3)) #-1到1的随机数二维数组
np.random.randint(10,20,size = (3,3)) #范围内随机数二维数组
  • numpy属性
import numpy as np

#基本属性
arr = np.random.randint(1,9,size = (3,3))
print(arr.ndim) #维数,输出: 2
print(arr.shape) #形状,输出: (3,3)
print(arr.dtype) #类型,输出: int32
print(arr.itemsize) #字节长度,输出: 4
print(arr.size) #大小,输出: 9(=3x3)

#改变数组形状
arr2 = np.random.randint(1,9,size = (2,5))
#shape修改
arr2.shape(5,2) # 5x2=2x5 !!! 必须相等,也可以arr2.shape(5,-1),让电脑自己算
print(arr2)
#reshape修改
arr3 = np.arange(9)
arr4 = arr.reshape(3,3)
print(arr4)
arr4[0][1] = 100 #改变新数组的一个元素
print(arr4)
print(arr3) #发现原数组对应的数据也被改了,类似浅拷贝
#所以,一般这样创建
arr5 = np.arange(9).resahpe(3,3)
  • numpy基本操作
    数组不再用循环,直接就能批量运算
import numpy as np

#数组与标量运算
arr = np.anrange(0,9).reshape(3,3)
print(arr)
print(arr + 2)

#数组间运算
arr1 = np.array([
    [1,2,3],
    [4,5,6]
])
arr2 = np.array([
    [10,20,30],
    [40,50,60]
])
print(arr1+arr2) #大小要相等,才能一一对应
'''
    输出:[
        [11,22,33],
        [44,55,66]
        ]
'''

#数组的矩阵积(矩阵点积)
arr1 = np.array([
    [1,2,3],
    [4,5,6]
])
arr2 = np.array([
    [10,20],
    [40,50,,
    [70,80]
])
print(np.dot(arr1,arr2))

#多维数组的索引和切片
arr3 = np.array([
    [
        [1,2],
        [3,4]
    ],
    [
        [5,6],
        [7,8]
    ]
])
print(arr3[0][1][0]) #输出: 3
print(arr3[1,:,1]) #输出: [6,8]
print(arr3[:,:,0]) #输出: [[1,3],[5,7]]

#花式索引
arr = np.random.randint(1,9,size = (8,4))
print(arr)
print(arr[(0,3,5)]) #获取0,3,5行数据
print(arr[[0,3,5],[0,3,2]]) #获取0,0 3,3 5,2 数据
print(arr[np.ix_([0,3,5],[0,3,2])] #索引器,分别获取0,3,5行的0,3,2数据,返回一个3x3数组

#布尔索引
arr2 = np.random.random((3,3))
print(arr2)
arr3 = arr2 < 0.5
print(arr3) #布尔值构成的3x3数组
#应用
name = np.array('joe','susan','tom')
score = np.array([
    [70,80,90],
    [77,88,99],
    [66,86,96]
])
classes = np.array('语文','数学','英语')
print(score[name = 'joe']) #输出第一行数据
name2 = name=='joe' #name2为布尔一维数组[true,false,false]
score[name2].reshape(-1) #相当于score[[true,false,false]],只输出第一行
score[name = 'joe',classes = '数学'] 
#输出: [80],相当于score[[true,false,false],[false,true,false]]

#数组转置
arr2 = arr.T
  • numpy常用一元函数
    np.abs(arr)绝对值
    np.sqrt(arr)平方根
    np.exp(arr)计算指数e的多少次方
    np.log2(arr)log默认为10
    np.isnan(arr)判断is not a number?
    np.isfinite(arr)有穷的
    np.isinf(arr)无穷的
    np.sin(arr)各种三角函数和反三角函数

  • numpy常用二元函数
    np.dot(arr1,arr2)点乘
    np.greater(arr1,arr2)比较if arr1>arr2
    np.logical_and np.logial_or np.logical_xor相当于 与 或 异或
    np.power(arr,3)

  • numpy聚合函数
    arr.min() arr.max() arr.sum() arr.mean() arr.std()最小 最大 总和 平均 标准差
    参数加上axis = 0按列算,axis = 1按行算

  • np.where函数,三元表达式x if condition else y的矢量化版本
    语法:np.where(codition,x,y)
    np.where([[True,False],[True,True]],[[1,2],[3,4]],[[9,8],[7,6]])
    输出: [ [ 1 , 8 ] , [ 3 , 4 ] ]

  • unique去重
    arr = np.array(['a','b','c','a','b'])
    arr2 = np.unique(arr)

  • loc 和 iloc
    loc用于标签名,比如arr.loc['A','B']
    iloc用于标签编号,比如arr.iloc[:,1:3]

posted @ 2019-06-28 10:02  鹏懿如斯  阅读(268)  评论(0编辑  收藏  举报