1. 程式人生 > 實用技巧 >鞏固複習(對以前的隨筆總結)_05

鞏固複習(對以前的隨筆總結)_05

PageRank演算法
def create(q,graph,N):
    #compute Probability Matrix
    L = [[(1-q)/N]*N for i in range(N)]
    for node,edges in enumerate(graph):
        num_edge = len(edges)
        for each in edges:
            L[each][node] += q/num_edge
    return L
def transform(A):
    n,m = len(A),len(A[0])
    new_A 
= [[A[j][i] for j in range(n) ] for i in range(m)] return new_A def mul(A,B): n = len(A) m = len(B[0]) B = transform(B) next = [[0]*m for i in range(n)] for i in range(n): row = A[i] for j in range(m): col = B[j] next[i][j] = sum([row[k]*col[k] for
k in range(n)]) return next def power(A,N): n = len(A) assert(len(A[0])==n) final_ans,temp = A,A N-=1 while N>0: if N&1: final_ans = mul(final_ans,temp) temp = mul(temp,temp) N >>=1 return final_ans def PageRank(q,graph,N): X
= [[1] for i in range(N)] A = create(q,graph,N) X = mul(power(A,20),X) return X print(PageRank(0.85,[[1,2],[2],[0]],3)) ———————————————— 原文連結:https://blog.csdn.net/pp634077956/java/article/details/52604137

窮人版PageRank演算法的Python實現
#用於儲存圖
class Graph():
    def __init__(self):
        self.linked_node_map = {}#鄰接表,
        self.PR_map ={}#儲存每個節點的入度
    
    #新增節點
    def add_node(self, node_id):
        if node_id not in self.linked_node_map:
            self.linked_node_map[node_id] = set({})
            self.PR_map[node_id] = 0
        else:
            print("這個節點已經存在")
    
    #增加一個從Node1指向node2的邊。允許新增新節點
    def add_link(self, node1, node2):
        if node1 not in self.linked_node_map:
            self.add_node(node1)
        if node2 not in self.linked_node_map:
            self.add_node(node2)
        self.linked_node_map[node1].add(node2)#為node1新增一個鄰接節點,表示ndoe2引用了node1
    
    #計算pr
    def get_PR(self, epoch_num=10, d=0.5):#配置迭代輪數,以及阻尼係數
        for i in range(epoch_num):
            for node in self.PR_map:#遍歷每一個節點
                self.PR_map[node] = (1-d) + d*sum([self.PR_map[temp_node] for temp_node in self.linked_node_map[node]])#原始版公式
            print(self.PR_map)
            

edges = [[1,2], [3,2], [3,5], [1,3], [2,3], [3, 1], [5,1]]#模擬的一個網頁連結網路       
if __name__ == '__main__':
    graph = Graph()
    for edge in edges:
        graph.add_link(edge[0], edge[1])
    graph.get_PR()

分解質因數
把一個合數分解成若干個質因數的乘積的形式,即求質因數的過程叫做分解質因數。

Python練習題問題如下:
要求:將一個正整數分解質因數;例如您輸入90,分解列印90=2*3*3*5。
Python解題思路分析:
這道題需要分三部分來分解,具體分解說明如下。
1、首先當這個質數恰等於n的情況下,則說明分解質因數的過程已經結束,打印出即可。
2、如果遇到n<>k,但n能被k整除的情況,則應打印出k的值。同時用n除以k的商,作為新的正整數你n,之後再重複執行第一步的操作。
3、如果n不能被k整除時,那麼用k+1作為k的值,再來重複執行第一步的作業系統。

def reduceNum(n):
    print ('{} = '.format(n))
    if not isinstance(n, int) or n <= 0 :
        print ('請輸入一個正確的數字')
        exit(0)
    elif n in [1] :
        # 如果 n 為 1
        print('{}'.format(n))
    while n not in [1] : # 迴圈保證遞迴
        for index in range(2, n + 1) :
            if n % index == 0:
                n //= index # n 等於 n//index
                if n == 1: 
                    print (index) 
                else : # index 一定是素數
                    print ('{} *'.format(index),end = "   ")
                break
reduceNum(90)
reduceNum(100)


計算皮球下落速度

問題簡述:假設一支皮球從100米高度自由落下。條件,每次落地後反跳回原高度的一半後,再落下。
要求:算出這支皮球,在它在第10次落地時,共經過多少米?第10次反彈多高?
解題思路
總共初始高度 100 米
高度 每次彈起一半距離

每一次彈起  上升的高度和下降的高度 是一次的距離

每一次彈起,高度都會是之前的一半
Sn = 100.0
Hn = Sn / 2
 
for n in range(2,11):
    Sn += 2 * Hn
    Hn /= 2
 
print ('總共經過  %.2f 米' % Sn)
print ('第十次反彈 %.2f 米' % Hn)


給定年月日,判斷是這一年的第幾天
# 輸入年月日
year = int(input('year:'))
month = int(input('month:'))
day = int(input('day:'))

# 將正常情況下,每一個月的累計天數放入到元組中進行儲存
months = (0,31,59,90,120,151,181,212,243,273,304,334)

if 0 < month <= 12:
    # 如果輸入的資料正確,月份在 1~12 之間
    sum_days = months[month - 1]
    # 總天數就為 列表中的天數,索引值根據 輸入的月份進行選擇
else:
    print ('資料錯誤,請重新輸入')

# 加上輸入的日期
sum_days += day

# 預設不是閏年
leap = 0 

# 判斷是否是閏年,被 400 整除,可以整除4 但是不能被 100 除掉 
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
    leap = 1
    # 如果為 1 則表示 這一年是閏年

if (leap == 1) and (month > 2):
    # 當這一年是閏年,並且月份大於 2 時,說明存在 29 日,所以總天數再增加 1
    sum_days += 1

print ('這是 %d 年的第 %d 天.' % (year,sum_days))


實驗1-5
Django暫時停止更新,先把學校實驗報告弄完


'''
計算
1.輸入半徑,輸出面積和周長
2.輸入面積,輸出半徑及周長
3.輸入周長,輸出半徑及面積
'''
'''1.輸入半徑,輸出面積和周長'''
from math import pi

'''定義半徑'''
r = int(input("請輸入半徑的值(整數)"))
if r <= 0 :
    exit("請重新輸入半徑")
''' S 面積: pi * r * r '''
S = pi * pow(r,2)
print(" 半徑為 %d 的圓,面積為 %.2f"%(r,S))
'''C 周長: C = 2 * pi * r '''
C = 2 * pi * r
print(" 半徑為 %d 的圓,周長為 %.2f"%(r,C))

'''2.輸入面積,輸出半徑及周長'''
from math import pi,sqrt

S = float(input("請輸入圓的面積(支援小數格式)"))
if S < 0 :
    exit("請重新輸入面積")
'''r 半徑: r = sqrt(S/pi)'''
r = sqrt(S/pi)

print("面積為 %.2f 的圓,半徑為 %.2f"%(S,r))
'''C 周長: C = 2 * pi * r '''
C = 2 * pi * r
print("面積為 %.2f 的圓,周長為 %.2f"%(S,C))

'''3.輸入周長,輸出半徑及面積'''
from math import pi

C = float(input("請輸入圓的周長(支援小數格式)"))
if C < 0 :
    exit("請重新輸入周長")
'''r 半徑: r = C/(2*pi)'''
r = C/(2*pi)

print("周長為 %.2f 的圓,半徑為 %.2f"%(C,r))
''' S 面積: pi * r * r '''
S = pi * pow(r,2)
print("周長為 %.2f 的圓,面積為 %.2f"%(C,S))


'''
資料結構
列表練習
 1.建立列表物件 [110,'dog','cat',120,'apple']
 2.在字串 'dog' 和 'cat' 之間插入空列表
 3.刪除 'apple' 這個字串
 4.查找出 110、120 兩個數值,並以 10 為乘數做自乘運算
'''
'''1.建立列表物件 [110,'dog','cat',120,'apple']'''
# '''建立一個名為 lst 的列表物件'''
lst = [110,'dog','cat',120,'apple']
print(lst)

'''2.在字串 'dog' 和 'cat' 之間插入空列表'''
lst = [110,'dog','cat',120,'apple']
'''新增元素到 'dog' 和 'cat' 之間'''
lst.insert(2,[])
print(lst)

'''3.刪除 'apple' 這個字串'''
lst = [110,'dog','cat',120,'apple']
'''刪除最後一個元素'''
lst.pop()
print(lst)

'''4.查找出 110、120 兩個數值,並以 10 為乘數做自乘運算'''
lst = [110,'dog','cat',120,'apple']
try:
    '''如果找不到資料,進行異常處理'''
    lst[lst.index(110)] *= 10
    lst[lst.index(120)] *= 10
except Exception as e:
    print(e)
print(lst)


'''
元組練習
 1.建立列表 ['pen','paper',10,False,2.5] 賦給變數並檢視變數的型別
 2.將變數轉換為 tuple 型別,檢視變數的型別
 3.查詢元組中的元素 False 的位置
 4.根據獲得的位置提取元素
'''
'''1.建立列表 ['pen','paper',10,False,2.5] 賦給變數並檢視變數的型別'''
lst = ['pen','paper',10,False,2.5]
'''檢視變數型別'''
print("變數的型別",type(lst))

'''2.將變數轉換為 tuple 型別,檢視變數的型別'''
lst = tuple(lst)
print("變數的型別",type(lst))

'''3.查詢元組中的元素 False 的位置'''
if False in lst:
    print("False 的位置為(從0開始): ",lst.index(False))
    '''4.根據獲得的位置提取元素'''
    print("根據獲得的位置提取的元素為: ",lst[lst.index(False)])
else:
    print("不在元組中")


'''
1.建立字典{‘Math’:96,’English’:86,’Chinese’:95.5,
’Biology’:86,’Physics’:None}
2.在字典中新增鍵對{‘Histore’:88}
3.刪除{’Physics’:None}鍵值對
4.將鍵‘Chinese’所對應的值進行四捨五入後取整
5.查詢鍵“Math”的對應值
'''
'''1.建立字典'''
dic = {'Math':96,'English':86,'Chinese':95.5,'Biology':86,'Physics':None}
print(dic)

'''2.新增鍵值對'''
dic['Histore'] = 88
print(dic)

'''3.刪除{’Physics’:None}鍵值對'''
del dic['Physics']
print(dic)

'''4.將鍵‘Chinese’所對應的值進行四捨五入後取整'''
print(round(dic['Chinese']))

'''5.查詢鍵“Math”的對應值'''
print(dic['Math'])


'''
1.建立列表[‘apple’,’pear’,’watermelon’,’peach’]並賦給變數
2.用list()建立列表[‘pear’,’banana’,’orange’,’peach’,’grape’],並賦給變數
3.將建立的兩個列表物件轉換為集合型別
4.求兩個集合的並集、交集和差集
'''
'''1.建立列表'''
lst = ['apple','pear','watermelon','peach']
print(lst)

'''2.用list()建立,並賦給變數'''
lstTwo = list(('pear','banana','orange','peach','grape'))
print(lstTwo)

'''3.將建立的兩個列表物件轉換為集合型別'''
lst = set(lst)
lstTwo = set(lstTwo)

'''4.求兩個集合的並集、交集和差集'''
print("並集是:",lst | lstTwo)
print("交集是:",lst & lstTwo)
print("差集:")
print(lst - lstTwo)
print(lstTwo - lst)


'''
1 輸出數字金字塔
(1)設定輸入語句,輸入數字
(2)建立變數來存放金字塔層數
(3)編寫巢狀迴圈,控制變數存放每一層的長度
(4)設定條件來列印每一行輸出的數字
(5)輸出列印結果
'''
num = int(input("請輸入金字塔的層數"))
'''cs 層數'''
cs = 1
while cs <= num:
    kk = 1
    t = cs
    length = 2*t - 1
    while kk <= length:
        if kk == 1:
            if kk == length:
                print(format(t,str(2*num-1)+"d"),'\n')
                break
            else:
                print(format(t,str(2*num+1 - 2*cs) + "d"),"",end = "")
                t -= 1
        else:
            if kk == length:
                '''最右側數字 length 位置上數字為 t'''
                print(t,"\n")
                break
            elif kk <= length/2:
                '''到中間的數字不斷減小'''
                print(t,"",end = "")
                t -= 1
            else:
                '''中間的數字到右側的數字不斷增大'''
                print(t,"",end = "")
                t += 1
        kk += 1
    '''層數加 1'''
    cs += 1


'''
(1)使用自定義函式,完成對程式的模組化
(2)學生資訊至少包括:姓名、性別及手機號
(3)該系統具有的功能:新增、刪除、修改、顯示、退出系統
'''
'''建立一個容納所有學生的基本資訊的列表'''
stusInfo = []

def menu():
    '''定義頁面顯示'''
    print('-'*20)
    print('學生管理系統')
    print('1.新增學生資訊')
    print('2.刪除學生資訊')
    print('3.修改學生資訊')
    print('4.顯示所有學生資訊')
    print('0.退出系統')
    print('-' * 20)

def addStuInfo():
    '''新增學生資訊'''

    '''設定變數容納學生基本資訊'''
    newStuName = input('請輸入新學生的姓名')
    newStuGender = input('請輸入新學生的性別')
    newStuPhone = input('請輸入新學生的手機號')

    '''設定字典將變數儲存'''
    newStudent = {}
    newStudent['name'] = newStuName
    newStudent['gender'] = newStuGender
    newStudent['phone'] = newStuPhone

    '''新增到資訊中'''
    stusInfo.append(newStudent)

def delStuInfo():
    '''刪除學生資訊'''

    showStusInfo()

    defStuId = int(input('請輸入要刪除的序號:'))

    '''從列表中刪除 該學生'''
    del stusInfo[defStuId - 1]

def changeStuInfo():
    '''修改學生資訊'''
    showStusInfo()
    '''檢視修改的學生序號'''
    stuId = int(input("請輸入需要修改的學生的序號: "))

    changeStuName = input('請輸入修改後的學生的姓名')
    changeStuGender = input('請輸入修改後的學生的性別')
    changeStuPhone = input('請輸入修改後的學生的手機號')

    '''對列表修改學生資訊'''
    stusInfo[stuId - 1]['name'] = changeStuName
    stusInfo[stuId - 1]['gender'] = changeStuGender
    stusInfo[stuId - 1]['phone'] = changeStuPhone

def showStusInfo():
    print('-'*30)
    print("學生的資訊如下:")
    print('-'*30)
    print('序號   姓名  性別  手機號碼')

    '''展示學生序號(位置),姓名,性別,手機號碼'''
    stuAddr = 1
    for stuTemp in stusInfo:
        print("%d   %s  %s  %s"%(stuAddr,stuTemp['name'],stuTemp['gender'],stuTemp['phone']))
        stuAddr += 1

def main():
    '''主函式'''
    while True:
        '''顯示選單'''
        menu()
        keyNum = int(input("請輸入功能對應的數字"))
        if keyNum == 1:
            addStuInfo()
        elif keyNum == 2:
            delStuInfo()
        elif keyNum == 3:
            changeStuInfo()
        elif keyNum == 4:
            showStusInfo()
        elif keyNum == 0:
            print("歡迎下次使用")
            break


if __name__ == '__main__':
    main()


import numpy as np
'''一維陣列'''

'''np.array 方法'''

print(np.array([1,2,3,4]))
# [1 2 3 4]
print(np.array((1,2,3,4)))
# [1 2 3 4]
print(np.array(range(4)))
# [0 1 2 3]

'''np.arange 方法'''
print(np.arange(10))
# [0 1 2 3 4 5 6 7 8 9]

'''np.linspace 方法'''
print(np.linspace(0,10,11))
# [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]
print(np.linspace(0,10,11,endpoint = False))
# [0.         0.90909091 1.81818182 2.72727273 3.63636364 4.54545455
#  5.45454545 6.36363636 7.27272727 8.18181818 9.09090909]

'''np.logspace 方法'''
print(np.logspace(0,100,10))
# [1.00000000e+000 1.29154967e+011 1.66810054e+022 2.15443469e+033
#  2.78255940e+044 3.59381366e+055 4.64158883e+066 5.99484250e+077
#  7.74263683e+088 1.00000000e+100]
print(np.logspace(1,4,4,base = 2))
# [ 2.  4.  8. 16.]

'''zeros 方法'''
print(np.zeros(3))
# [0. 0. 0.]

'''ones 方法'''
print(np.ones(3))
# [1. 1. 1.]


'''二維陣列'''

'''np.array 方法'''
print(np.array([[1,2,3],[4,5,6]]))
# [[1 2 3]
#  [4 5 6]]

'''np.identify 方法'''
print(np.identity(3))
# [[1. 0. 0.]
#  [0. 1. 0.]
#  [0. 0. 1.]]

'''np.empty 方法'''
print(np.empty((3,3)))
# [[1. 0. 0.]
#  [0. 1. 0.]
#  [0. 0. 1.]]

'''np.zeros 方法'''
print(np.zeros((3,3)))
# [[0. 0. 0.]
#  [0. 0. 0.]
#  [0. 0. 0.]]

'''np.ones 方法'''
print(np.ones((3,3)))
# [[1. 1. 1.]
#  [1. 1. 1.]
#  [1. 1. 1.]]


import numpy as np

'''一維陣列'''

'''np.random.randint 方法'''
print(np.random.randint(0,6,3))
# [4 2 1]

'''np.random.rand 方法'''
print(np.random.rand(10))
# [0.12646424 0.59660184 0.52361248 0.1206141  0.28359949 0.46069696
#  0.18397493 0.73839455 0.99115088 0.98297331]

'''np.random.standard_normal 方法'''
print(np.random.standard_normal(3))
# [-0.12944733 -0.32607943  0.58582095]


'''二維陣列'''

'''np.random.randint 方法'''
print(np.random.randint(0,6,(3,3)))
# [[0 0 0]
#  [4 4 0]
#  [5 0 3]]

'''多維陣列'''
print(np.random.standard_normal((3,4,2)))
# [[[-0.79751104 -1.40814148]
#   [-1.06189896  1.19993648]
#   [ 1.68883868  0.09190824]
#   [ 0.33723433  0.28246094]]
#
#  [[ 0.3065646   1.1177714 ]
#   [-0.48928572  0.55461195]
#   [ 0.3880272  -2.27673705]
#   [-0.97869759 -0.07330554]]
#
#  [[ 0.62155155 -0.17690222]
#   [ 1.61473949 -0.34930031]
#   [-1.41535777  1.32646137]
#   [-0.22865775 -2.00845225]]]


import numpy as np

n = np.array([10,20,30,40])

print(n + 5)
# [15 25 35 45]
print(n - 10)
# [ 0 10 20 30]
print(n * 2)
# [20 40 60 80]
print(n / 3)
# [ 3.33333333  6.66666667 10.         13.33333333]
print(n // 3)
# [ 3  6 10 13]
print(n % 3)
# [1 2 0 1]
print(n ** 2)
# [ 100  400  900 1600]

n = np.array([1,2,3,4])
print(2 ** n)
# [ 2  4  8 16]
print(16//n)
# [16  8  5  4]

print(np.array([1,2,3,4]) + np.array([1,1,2,2]))
# [2 3 5 6]
print(np.array([1,2,3,4]) + np.array(4))
# [5 6 7 8]

print(n)
# [1 2 3 4]

print(n + n)
# [2 4 6 8]
print(n - n)
# [0 0 0 0]
print(n * n)
# [ 1  4  9 16]
print(n / n)
# [1. 1. 1. 1.]
print(n ** n)
# [  1   4  27 256]

x = np.array([4,7,3])
print(np.argsort(x))
# [2 0 1]

print(x.argmax())
# 1
print(x.argmin())
# 2

print(np.sort(x))
# [3 4 7]

print(np.where(x < 5,0,1))

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

x.resize((2,5))
print(x)
# [[1 2 3 4 5]
#  [6 7 8 9 0]]

print(np.piecewise(x,[x<3],[lambda x:x + 1]))
# [[2 3 0 0 0]
#  [0 0 0 0 1]]


import pandas as pd
import numpy as np

'''對 sepal_length 這一列進行分析'''
irisSepalLength = np.loadtxt('iris.csv')
print(irisSepalLength[:5])
# [5.1 4.9 4.7 4.6 5. ]

'''對資料進行排序'''
irisSepalLength.sort()
print(irisSepalLength[:15])
# [4.3 4.4 4.4 4.4 4.5 4.6 4.6 4.6 4.6 4.7 4.7 4.8 4.8 4.8 4.8]

'''檢視去重後的資料集'''
print(np.unique(irisSepalLength)[:15])
# [4.3 4.4 4.5 4.6 4.7 4.8 4.9 5.  5.1 5.2 5.3 5.4 5.5 5.6 5.7]

'''檢視長度的總和'''
print(np.sum(irisSepalLength))
# 876.5

'''累計和'''
print(np.cumsum(irisSepalLength)[:10])
# [ 4.3  8.7 13.1 17.5 22.  26.6 31.2 35.8 40.4 45.1]


'''均值'''
print(np.mean(irisSepalLength))
# 5.843333333333334

'''標準差'''
print(np.std(irisSepalLength))
# 0.8253012917851409

'''方差'''
print(np.var(irisSepalLength))
# 0.6811222222222223

'''最小值'''
print(np.min(irisSepalLength))
# 4.3

'''最大值'''
print(np.max(irisSepalLength))
# 7.9


import pandas as pd

'''建立 Series 物件 s'''
s = pd.Series(range(1,20,5))
print(s)
# 0     1
# 1     6
# 2    11
# 3    16
# dtype: int64

s = pd.Series({'語文':90,'數學':92,'物理':88,'化學':99})
print(s)
# 語文    90
# 數學    92
# 物理    88
# 化學    99
# dtype: int64

'''修改資料'''
s['語文'] = 100
print(s)
# 語文    100
# 數學     92
# 物理     88
# 化學     99
# dtype: int64

'''使用絕對值'''
print(abs(s))
# 語文    100
# 數學     92
# 物理     88
# 化學     99
# dtype: int64

'''對資料列加字尾'''
# s.add_suffix('字尾')

'''檢視某些資料是否滿足條件'''
print(s.between(90,99,inclusive = True))
# 語文    False
# 數學     True
# 物理    False
# 化學     True
# dtype: bool

'''檢視屬性最大的列名'''
print(s.idxmax())
# 語文

'''檢視屬性最小的列名'''
print(s.idxmin())
# 物理

'''大於 95 的列'''
print(s[s > 95])
# 語文    100
# 化學     99
# dtype: int64

'''檢視中值'''
print(s.median())
# 95.5

'''大於中值的列'''
print(s[s > s.median()])
# 語文    100
# 化學     99
# dtype: int64

'''檢視最小的 3 個值'''
print(s.nsmallest(3))
# 物理    88
# 數學    92
# 化學    99
# dtype: int64


'''檢視最大的 3 個值'''
print(s.nlargest(3))
# 語文    100
# 化學     99
# 數學     92
# dtype: int64

'''兩個 Series 物件進行相加'''
print(pd.Series(range(5)) + pd.Series(range(7,12)))
# 0     7
# 1     9
# 2    11
# 3    13
# 4    15
# dtype: int64

'''對 Series 物件使用函式'''
print(pd.Series(range(5)).pipe(lambda x,y:(x**y),4))
# 0      0
# 1      1
# 2     16
# 3     81
# 4    256
# dtype: int64

print(pd.Series(range(5)).pipe(lambda x:x + 3))
# 0    3
# 1    4
# 2    5
# 3    6
# 4    7
# dtype: int64

print(pd.Series(range(5)).apply(lambda x:x + 3))
# 0    3
# 1    4
# 2    5
# 3    6
# 4    7
# dtype: int64

'''檢視標準差方差'''
print(s)
print(s.std())
# 5.737304826019502
print(s.var())
# 32.916666666666664

'''檢視是否全部為真'''
print(any(pd.Series([1,0,1])))
# True

print(all(pd.Series([1,0,1])))
# False


import pandas as pd
import numpy as np

'''建立一個 DataFrame 物件'''
df = pd.DataFrame(np.random.randint(1,5,(5,3)),index = range(5),columns = ['A','B','C'])
print(df)
#    A  B  C
# 0  4  4  2
# 1  1  4  1
# 2  4  3  4
# 3  3  1  3
# 4  2  3  1

'''讀取資料'''
market = pd.read_excel('超市營業額.xlsx')
print(market.head())
#      工號  姓名          日期           時段     交易額   櫃檯
# 0  1001  張三  2019-03-01   9:00-14:00  1664.0  化妝品
# 1  1002  李四  2019-03-01  14:00-21:00   954.0  化妝品
# 2  1003  王五  2019-03-01   9:00-14:00  1407.0   食品
# 3  1004  趙六  2019-03-01  14:00-21:00  1320.0   食品
# 4  1005  周七  2019-03-01   9:00-14:00   994.0  日用品


'''檢視不連續行的資料'''
print(market.iloc[[1,8,19],:])
#       工號  姓名          日期           時段     交易額   櫃檯
# 1   1002  李四  2019-03-01  14:00-21:00   954.0  化妝品
# 8   1001  張三  2019-03-02   9:00-14:00  1530.0  化妝品
# 19  1004  趙六  2019-03-03  14:00-21:00  1236.0   食品

print(market.iloc[[1,8,19],[1,4]])
#     姓名     交易額
# 1   李四   954.0
# 8   張三  1530.0
# 19  趙六  1236.0

'''檢視前五條記錄的 姓名 時段 和 交易額'''
print(market[['姓名','時段','交易額']].head())
#    姓名           時段     交易額
# 0  張三   9:00-14:00  1664.0
# 1  李四  14:00-21:00   954.0
# 2  王五   9:00-14:00  1407.0
# 3  趙六  14:00-21:00  1320.0
# 4  周七   9:00-14:00   994.0

print(market.loc[[3,4,7],['姓名','時段','櫃檯']])
#    姓名           時段    櫃檯
# 3  趙六  14:00-21:00    食品
# 4  周七   9:00-14:00   日用品
# 7  張三  14:00-21:00  蔬菜水果

'''檢視交易額大於 2000 的資料'''
print(market[market.交易額 > 1500].head())
#       工號  姓名          日期          時段     交易額    櫃檯
# 0   1001  張三  2019-03-01  9:00-14:00  1664.0   化妝品
# 8   1001  張三  2019-03-02  9:00-14:00  1530.0   化妝品
# 14  1002  李四  2019-03-02  9:00-14:00  1649.0  蔬菜水果
# 18  1003  王五  2019-03-03  9:00-14:00  1713.0    食品
# 20  1005  周七  2019-03-03  9:00-14:00  1592.0   日用品

'''檢視交易額的總和'''
print(market['交易額'].sum())
# 327257.0

print(market[market['時段'] == '9:00-14:00']['交易額'].sum())
# 176029.0

'''檢視某員工在 14:00-21:00 的交易資料'''
print(market[(market.姓名 == '張三') & (market.時段 == '14:00-21:00')].head())
#       工號  姓名          日期           時段     交易額    櫃檯
# 7   1001  張三  2019-03-01  14:00-21:00  1442.0  蔬菜水果
# 39  1001  張三  2019-03-05  14:00-21:00   856.0  蔬菜水果
# 73  1001  張三  2019-03-10  14:00-21:00  1040.0   化妝品
# 91  1001  張三  2019-03-12  14:00-21:00  1435.0    食品
# 99  1001  張三  2019-03-13  14:00-21:00  1333.0    食品

'''檢視交易額在 1500 到 2500 的資料'''
print(market[market['交易額'].between(1500,2000)].head())
#       工號  姓名          日期          時段     交易額    櫃檯
# 0   1001  張三  2019-03-01  9:00-14:00  1664.0   化妝品
# 8   1001  張三  2019-03-02  9:00-14:00  1530.0   化妝品
# 14  1002  李四  2019-03-02  9:00-14:00  1649.0  蔬菜水果
# 18  1003  王五  2019-03-03  9:00-14:00  1713.0    食品
# 20  1005  周七  2019-03-03  9:00-14:00  1592.0   日用品

'''檢視描述'''
print(market['交易額'].describe())
# count      246.000000
# mean      1330.313008
# std        904.300720
# min         53.000000
# 25%       1031.250000
# 50%       1259.000000
# 75%       1523.000000
# max      12100.000000
# Name: 交易額, dtype: float64

print(market['交易額'].quantile([0,0.25,0.5,0.75,1]))
# 0.00       53.00
# 0.25     1031.25
# 0.50     1259.00
# 0.75     1523.00
# 1.00    12100.00
# Name: 交易額, dtype: float64

'''檢視中值'''
print(market['交易額'].median())
# 1259.0

'''檢視最大值'''
print(market['交易額'].max())
# 12100.0
print(market['交易額'].nlargest(5))
# 105    12100.0
# 223     9031.0
# 113     1798.0
# 188     1793.0
# 136     1791.0

'''檢視最小值'''
print(market['交易額'].min())
# 53.0
print(market['交易額'].nsmallest(5))
#  76      53.0
# 97      98.0
# 194    114.0
# 86     801.0
# 163    807.0
# Name: 交易額, dtype: float64


 

import pandas as pd

market = pd.read_excel('超市營業額.xlsx')
print(market.head())
#      工號  姓名          日期           時段     交易額   櫃檯
# 0  1001  張三  2019-03-01   9:00-14:00  1664.0  化妝品
# 1  1002  李四  2019-03-01  14:00-21:00   954.0  化妝品
# 2  1003  王五  2019-03-01   9:00-14:00  1407.0   食品
# 3  1004  趙六  2019-03-01  14:00-21:00  1320.0   食品
# 4  1005  周七  2019-03-01   9:00-14:00   994.0  日用品

'''對資料進行排序'''
print(market.sort_values(by = ['交易額','工號'],ascending = False).head())
#        工號  姓名          日期           時段      交易額    櫃檯
# 105  1001  張三  2019-03-14   9:00-14:00  12100.0   日用品
# 223  1003  王五  2019-03-28   9:00-14:00   9031.0    食品
# 113  1002  李四  2019-03-15   9:00-14:00   1798.0   日用品
# 188  1002  李四  2019-03-24  14:00-21:00   1793.0  蔬菜水果
# 136  1001  張三  2019-03-17  14:00-21:00   1791.0    食品

print(market.sort_values(by = ['交易額','工號'],ascending = True).head())
#        工號  姓名          日期           時段    交易額    櫃檯
# 76   1005  周七  2019-03-10   9:00-14:00   53.0   日用品
# 97   1002  李四  2019-03-13  14:00-21:00   98.0   日用品
# 194  1001  張三  2019-03-25  14:00-21:00  114.0   化妝品
# 86   1003  王五  2019-03-11   9:00-14:00  801.0  蔬菜水果
# 163  1006  錢八  2019-03-21   9:00-14:00  807.0  蔬菜水果


'''groupby 物件 的使用'''
print(market.groupby(by = lambda x:x%3)['交易額'].sum())
# 0    113851.0
# 1    108254.0
# 2    105152.0
# Name: 交易額, dtype: float64

'''檢視 櫃檯的交易額 '''
print(market.groupby(by = '櫃檯')['交易額'].sum())
# 櫃檯
# 化妝品     75389.0
# 日用品     88162.0
# 蔬菜水果    78532.0
# 食品      85174.0
# Name: 交易額, dtype: float64

'''檢視日期個數'''
print(market.groupby(by = '姓名')['日期'].count())
# 姓名
# 周七    42
# 張三    38
# 李四    47
# 王五    40
# 趙六    45
# 錢八    37
# Name: 日期, dtype: int64

'''將員工的營業額彙總出來'''
print(market.groupby(by = '姓名')['交易額'].sum().apply(int))
# 姓名
# 周七    47818
# 張三    58130
# 李四    58730
# 王五    58892
# 趙六    56069
# 錢八    47618
# Name: 交易額, dtype: int64

'''檢視交易額的 最大最小平均值和中值'''
print(market.groupby(by = '姓名').agg(['max','min','mean','median'])['交易額'])
#         max    min         mean  median
# 姓名
# 周七   1778.0   53.0  1195.450000  1134.5
# 張三  12100.0  114.0  1529.736842  1290.0
# 李四   1798.0   98.0  1249.574468  1276.0
# 王五   9031.0  801.0  1472.300000  1227.0
# 趙六   1775.0  825.0  1245.977778  1224.0
# 錢八   1737.0  807.0  1322.722222  1381.0

'''處理異常值'''
# 考慮使用其他資料替代

'''處理缺失值'''
print(market[market['交易額'].isnull()])
#        工號  姓名          日期           時段  交易額   櫃檯
# 110  1005  周七  2019-03-14  14:00-21:00  NaN  化妝品
# 124  1006  錢八  2019-03-16  14:00-21:00  NaN   食品
# 168  1005  周七  2019-03-21  14:00-21:00  NaN   食品
# 考慮使用 平均值 替換

'''處理重複值'''
# 考慮是否刪除資料
'''duplicated() 和 drop_duplicates()'''

'''使用透視表,檢視前五天的資料'''
print(market.pivot_table(values = '交易額',index = '姓名',columns = '日期',aggfunc = 'sum').iloc[:,:5])

print(market.pivot_table(values = '交易額',index = '姓名',columns = '櫃檯',aggfunc = 'count').iloc[:,:5])

'''使用交叉表,檢視員工和櫃檯的次數'''
print(pd.crosstab(market['姓名'],market['櫃檯']))
# 姓名
# 周七    9   11    14   8
# 張三   19    6     6   7
# 李四   16    9    18   4
# 王五    8    9     9  14
# 趙六   10   18     2  15
# 錢八    0    9    14  14

print(pd.crosstab(market['姓名'],market['日期']))
# 日期  2019-03-01  2019-03-02  2019-03-03  ...  2019-03-29  2019-03-30  2019-03-31
# 姓名                                      ...
# 周七           1           1           2  ...           1           1           2
# 張三           2           1           1  ...           1           2           0
# 李四           1           2           1  ...           2           2           2
# 王五           1           2           1  ...           1           1           1
# 趙六           1           1           2  ...           2           1           2
# 錢八           2           1           1  ...           1           1           1

print(pd.crosstab(market['姓名'],market['櫃檯'],market['交易額'],aggfunc = 'mean').apply(lambda x:round(x)))
# 櫃檯     化妝品     日用品    蔬菜水果      食品
# 姓名
# 周七  1190.0  1169.0  1174.0  1285.0
# 張三  1209.0  3105.0  1211.0  1323.0
# 李四  1279.0  1123.0  1292.0  1224.0
# 王五  1264.0  1262.0  1164.0  1925.0
# 趙六  1232.0  1294.0  1264.0  1196.0
# 錢八     NaN  1325.0  1326.0  1318.0

學生成績表資料包括:學號,姓名,高數,英語和計算機三門課成績,計算每個學生總分,每課程平均分,最高分和最低分
'''
每一個學生的總分,每個課程的平均分,最高分,最低分
'''
# 建立學生列表
stuLst = []

# 建立學生資訊
stu1 = {'學號':'1001','姓名':'小明','高數':95,'英語':88,'計算機':80}
stu2 = {'學號':'1002','姓名':'小李','高數':84,'英語':70,'計算機':60}
stu3 = {'學號':'1003','姓名':'小王','高數':79,'英語':78,'計算機':75}

# 將學生列表加入到學生資訊中
stuLst.append(stu1)
stuLst.append(stu2)
stuLst.append(stu3)

def sumScore(stuLst):
    '''計算每名學生的總分'''
    for stu in stuLst:
        print(stu['姓名'],"的三科總分是 ",stu['高數'] + stu['英語'] + stu['計算機'])

def meanScore(stuLst):
    '''計算課程的平均分'''
    sumProjectScore_gs = 0
    # 設定高數學科總分
    sumProjectScore_yy = 0
    # 設定英語學科總分
    sumProjectScore_jsj = 0
    # 設定計算機學科總分(_拼音縮寫)

    for stu in stuLst:
        sumProjectScore_gs += stu['高數']
        sumProjectScore_yy += stu['英語']
        sumProjectScore_jsj += stu['計算機']

    print("高數的平均分是 %.2f"%(sumProjectScore_gs//len(stuLst)))
    print("英語的平均分是 %.2f" % (sumProjectScore_yy // len(stuLst)))
    print("計算機的平均分是 %.2f" % (sumProjectScore_jsj // len(stuLst)))


def maxScore(stuLst):
    '''求最大值'''
    # 高數 英語 計算機
    gs = []
    yy = []
    jsj = []

    for stu in stuLst:
        gs.append(stu['高數'])
        yy.append(stu['英語'])
        jsj.append(stu['計算機'])
    print("高數的最高分是 %.2f"%(max(gs)))
    print("英語的最高分是 %.2f" % (max(yy)))
    print("計算機的最高分是 %.2f" % (max(jsj)))


def minScore(stuLst):
    '''求最小值'''
    # 高數 英語 計算機
    gs = []
    yy = []
    jsj = []

    for stu in stuLst:
        gs.append(stu['高數'])
        yy.append(stu['英語'])
        jsj.append(stu['計算機'])
    print("高數的最低分是 %.2f" % (min(gs)))
    print("英語的最低分是 %.2f" % (min(yy)))
    print("計算機的最低分是 %.2f" % (min(jsj)))


sumScore(stuLst)
meanScore(stuLst)
maxScore(stuLst)
minScore(stuLst)

四位玫瑰數

for i in range(1000,10000):
    t=str(i)
    if pow(eval(t[0]),4)+pow(eval(t[1]),4)+pow(eval(t[2]),4)+pow(eval(t[3]),4) == i:
        print(i)


四平方和
import math
def f(n):
    if isinstance(n,int):
        for i in range(round(math.sqrt(n))):
            for j in range(round(math.sqrt(n))):
                for k in range(round(math.sqrt(n))):
                    h = math.sqrt(n - i*i - j*j - k*k)
                    # 剪掉使用了的值
                    if h == int(h):
                        print("(%d,%d,%d,%d)"%(i,j,k,h))
                        return 
    else:
        print("(0,0,0,0)")

f(5)
f(12)
f("aaa")


學生管理系統-明日學院的
import re  # 匯入正則表示式模組
import os  # 匯入作業系統模組

filename = "students.txt"  # 定義儲存學生資訊的檔名


def menu():
    # 輸出選單
    print('''
    ╔———————學生資訊管理系統————————╗
    │                                              │
    │   =============== 功能選單 ===============   │
    │                                              │
    │   1 錄入學生資訊                             │
    │   2 查詢學生資訊                             │
    │   3 刪除學生資訊                             │
    │   4 修改學生資訊                             │
    │   5 排序                                     │
    │   6 統計學生總人數                           │
    │   7 顯示所有學生資訊                         │
    │   0 退出系統                                 │
    │  ==========================================  │
    │  說明:通過數字或↑↓方向鍵選擇選單          │
    ╚———————————————————————╝
    ''')


def main():
    ctrl = True  # 標記是否退出系統
    while (ctrl):
        menu()  # 顯示選單
        option = input("請選擇:")  # 選擇選單項
        option_str = re.sub("\D", "", option)  # 提取數字
        if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:
            option_int = int(option_str)
            if option_int == 0:  # 退出系統
                print('您已退出學生成績管理系統!')
                ctrl = False
            elif option_int == 1:  # 錄入學生成績資訊
                insert()
            elif option_int == 2:  # 查詢學生成績資訊
                search()
            elif option_int == 3:  # 刪除學生成績資訊
                delete()
            elif option_int == 4:  # 修改學生成績資訊
                modify()
            elif option_int == 5:  # 排序
                sort()
            elif option_int == 6:  # 統計學生總數
                total()
            elif option_int == 7:  # 顯示所有學生資訊
                show()


'''1 錄入學生資訊'''


def insert():
    stdentList = []        # 儲存學生資訊的列表
    mark = True  # 是否繼續新增
    while mark:
        id = input("請輸入ID(如 1001):")
        if not id:  # ID為空,跳出迴圈
            break
        name = input("請輸入名字:")
        if not name:  # 名字為空,跳出迴圈
            break
        try:
            english = int(input("請輸入英語成績:"))
            python = int(input("請輸入Python成績:"))
            c = int(input("請輸入C語言成績:"))
        except:
            print("輸入無效,不是整型數值....重新錄入資訊")
            continue
        stdent = {"id": id, "name": name, "english": english, "python": python, "c": c}  # 將輸入的學生資訊儲存到字典
        stdentList.append(stdent)  # 將學生字典新增到列表中
        inputMark = input("是否繼續新增?(y/n):")
        if inputMark == "y":  # 繼續新增
            mark = True
        else:  # 不繼續新增
            mark = False
    save(stdentList)  # 將學生資訊儲存到檔案
    print("學生資訊錄入完畢!!!")


# 將學生資訊儲存到檔案
def save(student):
    try:
        students_txt = open(filename, "a")  # 以追加模式開啟
    except Exception as e:
        students_txt = open(filename, "w")  # 檔案不存在,建立檔案並開啟
    for info in student:
        students_txt.write(str(info) + "\n")  # 按行儲存,新增換行符
    students_txt.close()  # 關閉檔案


'''2 查詢學生成績資訊'''


def search():
    mark = True
    student_query = []  # 儲存查詢結果的學生列表
    while mark:
        id = ""
        name = ""
        if os.path.exists(filename):  # 判斷檔案是否存在
            mode = input("按ID查輸入1;按姓名查輸入2:")
            if mode == "1":
                id = input("請輸入學生ID:")
            elif mode == "2":
                name = input("請輸入學生姓名:")
            else:
                print("您的輸入有誤,請重新輸入!")
                search()  # 重新查詢
            with open(filename, 'r') as file:  # 開啟檔案
                student = file.readlines()  # 讀取全部內容
                for list in student:
                    d = dict(eval(list))  # 字串轉字典
                    if id != "":  # 判斷是否按ID查
                        if d['id'] == id:
                            student_query.append(d)  # 將找到的學生資訊儲存到列表中
                    elif name != "":  # 判斷是否按姓名查
                        if d['name'] == name:
                            student_query.append(d)  # 將找到的學生資訊儲存到列表中
                show_student(student_query)  # 顯示查詢結果
                student_query.clear()  # 清空列表
                inputMark = input("是否繼續查詢?(y/n):")
                if inputMark == "y":
                    mark = True
                else:
                    mark = False
        else:
            print("暫未儲存資料資訊...")
            return


'''3 刪除學生成績資訊'''


def delete():
    mark = True  # 標記是否迴圈
    while mark:
        studentId = input("請輸入要刪除的學生ID:")
        if studentId != "":  # 判斷要刪除的學生是否存在
            if os.path.exists(filename):  # 判斷檔案是否存在
                with open(filename, 'r') as rfile:  # 開啟檔案
                    student_old = rfile.readlines()  # 讀取全部內容
            else:
                student_old = []
            ifdel = False  # 標記是否刪除
            if student_old:  # 如果存在學生資訊
                with open(filename, 'w') as wfile:  # 以寫方式開啟檔案
                    d = {}  # 定義空字典
                    for list in student_old:
                        d = dict(eval(list))  # 字串轉字典
                        if d['id'] != studentId:
                            wfile.write(str(d) + "\n")  # 將一條學生資訊寫入檔案
                        else:
                            ifdel = True  # 標記已經刪除
                    if ifdel:
                        print("ID為 %s 的學生資訊已經被刪除..." % studentId)
                    else:
                        print("沒有找到ID為 %s 的學生資訊..." % studentId)
            else:  # 不存在學生資訊
                print("無學生資訊...")
                break  # 退出迴圈
            show()  # 顯示全部學生資訊
            inputMark = input("是否繼續刪除?(y/n):")
            if inputMark == "y":
                mark = True  # 繼續刪除
            else:
                mark = False  # 退出刪除學生資訊功能


'''4 修改學生成績資訊'''


def modify():
    show()  # 顯示全部學生資訊
    if os.path.exists(filename):  # 判斷檔案是否存在
        with open(filename, 'r') as rfile:  # 開啟檔案
            student_old = rfile.readlines()  # 讀取全部內容
    else:
        return
    studentid = input("請輸入要修改的學生ID:")
    with open(filename, "w") as wfile:  # 以寫模式開啟檔案
        for student in student_old:
            d = dict(eval(student))  # 字串轉字典
            if d["id"] == studentid:  # 是否為要修改的學生
                print("找到了這名學生,可以修改他的資訊!")
                while True:  # 輸入要修改的資訊
                    try:
                        d["name"] = input("請輸入姓名:")
                        d["english"] = int(input("請輸入英語成績:"))
                        d["python"] = int(input("請輸入Python成績:"))
                        d["c"] = int(input("請輸入C語言成績:"))
                    except:
                        print("您的輸入有誤,請重新輸入。")
                    else:
                        break  # 跳出迴圈
                student = str(d)  # 將字典轉換為字串
                wfile.write(student + "\n")   # 將修改的資訊寫入到檔案
                print("修改成功!")
            else:
                wfile.write(student)  # 將未修改的資訊寫入到檔案
    mark = input("是否繼續修改其他學生資訊?(y/n):")
    if mark == "y":
        modify()  # 重新執行修改操作


'''5 排序'''


def sort():
    show()  # 顯示全部學生資訊
    if os.path.exists(filename):  # 判斷檔案是否存在
        with open(filename, 'r') as file:  # 開啟檔案
            student_old = file.readlines()  # 讀取全部內容
            student_new = []
        for list in student_old:
            d = dict(eval(list))  # 字串轉字典
            student_new.append(d)  # 將轉換後的字典新增到列表中
    else:
        return
    ascORdesc = input("請選擇(0升序;1降序):")
    if ascORdesc == "0":  # 按升序排序
        ascORdescBool = False           # 標記變數,為False表示升序排序
    elif ascORdesc == "1":  # 按降序排序
        ascORdescBool = True          # 標記變數,為True表示降序排序
    else:
        print("您的輸入有誤,請重新輸入!")
        sort()  
    mode = input("請選擇排序方式(1按英語成績排序;2按Python成績排序;3按C語言成績排序;0按總成績排序):")
    if mode == "1":  # 按英語成績排序
        student_new.sort(key=lambda x: x["english"], reverse=ascORdescBool)
    elif mode == "2":  # 按Python成績排序
        student_new.sort(key=lambda x: x["python"], reverse=ascORdescBool)
    elif mode == "3":  # 按C語言成績排序
        student_new.sort(key=lambda x: x["c"], reverse=ascORdescBool)
    elif mode == "0":  # 按總成績排序
        student_new.sort(key=lambda x: x["english"] + x["python"] + x["c"], reverse=ascORdescBool)
    else:
        print("您的輸入有誤,請重新輸入!")
        sort()
    show_student(student_new)  # 顯示排序結果


''' 6 統計學生總數'''


def total():
    if os.path.exists(filename):  # 判斷檔案是否存在
        with open(filename, 'r') as rfile:  # 開啟檔案
            student_old = rfile.readlines()  # 讀取全部內容
            if student_old:
                print("一共有 %d 名學生!" % len(student_old))
            else:
                print("還沒有錄入學生資訊!")
    else:
        print("暫未儲存資料資訊...")


''' 7 顯示所有學生資訊 '''


def show():
    student_new = []
    if os.path.exists(filename):  # 判斷檔案是否存在
        with open(filename, 'r') as rfile:  # 開啟檔案
            student_old = rfile.readlines()  # 讀取全部內容
        for list in student_old:
            student_new.append(eval(list))  # 將找到的學生資訊儲存到列表中
        if student_new:
            show_student(student_new)
    else:
        print("暫未儲存資料資訊...")


# 將儲存在列表中的學生資訊顯示出來
def show_student(studentList):
    if not studentList:
        print("無資料資訊 \n")
        return
    format_title = "{:^6}{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^10}"
    print(format_title.format("ID", "名字", "英語成績", "Python成績", "C語言成績", "總成績"))
    format_data = "{:^6}{:^12}\t{:^12}\t{:^12}\t{:^12}\t{:^12}"
    for info in studentList:
        print(format_data.format(info.get("id"), info.get("name"), str(info.get("english")), str(info.get("python")),
                                 str(info.get("c")),
                                 str(info.get("english") + info.get("python") + info.get("c")).center(12)))


if __name__ == "__main__":
    main()

定義函式,給定一個列表作為函式引數,將列表中的非數字字元去除
'''定義函式,給定一個列表作為函式引數,將列表中的非數字字元去除。'''
class list:
    def __init__(self,alist):
        self.alist=alist
    def remove_str(self):

        a=""
        for i in self.alist:
            b=str(i)
            a+=b
        "".join (filter(str.isdigit,a))
        print("".join(filter(str.isdigit,a)))
a=list([1,2,3,"q",6,"sd","[][]{"])
a.remove_str()

給定幾位數,檢視數根(使用函式實現)
def numRoot(num):
    '''定義數根函式'''
    if len(num) == 1:
        return int(num)
    else:
        nums = []
        for i in range(len(num)):
            # 對字串進行遍歷
            nums.append(int(num[i]))
        if sum(nums) >= 10:
            # 如果數值加起來大於 10
            numRoot(str(sum(nums)))
        else:
            # 輸出樹根
            print(sum(nums))

num = input("請輸入一個數,檢視它的數根")
numRoot(num)

水果系統(面向過程,面向物件)
fruit = []

def menu():
    print(
        '''
        ********************水果超市********************  (面向物件,面向過程)
                1. 查詢全部水果
                2. 查詢指定名稱的水果
                3. 增加水果(增加到資料庫)
                4. 修改水果數量或者價格
                5. 刪除水果
                6. 按照價格排序
                7. 退出系統
        ***********************************************
        '''
        )

def showFruit():
    '''功能1 查詢全部水果'''
    print('-' * 30)
    print("水果的資訊如下:")
    print('-' * 30)
    print('序號 水果名  價格  數量')
    fru_id = 1
    for fru_temp in fruit:
        print("%s   %s   %s    %s "%(fru_id,fru_temp['name'],fru_temp['price'],fru_temp['num']))
        fru_id += 1

def searchFruitName():
    '''功能2 查詢指定名稱的水果'''
    showFruit()
    fru_name = input("請輸入想要查詢的水果名稱")
    fru_id = 1
    for fru in fruit:
        if fru_name in fru['name']:
            print("該水果資訊如下:")
            print("%d   %s  %s    %s " % (fru_id, fru['name'], fru['price'], fru['num']))
            return
        fru_id += 1
    print("沒有查詢到該水果名稱")


def addFruit():
    '''功能3 增加水果(增加到資料庫)'''
    newFruitName = input('請輸入新水果的名稱')
    newFruitPrice = input('請輸入新水果的價格')
    newFruitNum =  input('請輸入新水果的數量')

    newFruit = {}
    newFruit['name'] = newFruitName
    newFruit['price'] = newFruitPrice
    newFruit['num'] = newFruitNum

    fruit.append(newFruit)


def changeFruit():
    '''功能4 修改水果數量或者價格'''
    showFruit()

    fru_id = int(input("請輸入需要修改的水果的序號: "))

    changeFruitName = input('請輸入修改後的水果的名稱')
    changeFruitPrice = input('請輸入修改後的水果的價格')
    changeFruitNum = input('請輸入修改後的水果的數量')

    fruit[fru_id - 1]['name'] = changeFruitName
    fruit[fru_id - 1]['price'] = changeFruitPrice
    fruit[fru_id - 1]['num'] = changeFruitNum

def delFruit():
    '''功能5 刪除水果'''
    showFruit()
    delFruitId = int(input('請輸入要刪除的序號:'))
    del fruit[delFruitId - 1]

def sortFruit():
    '''功能6 按照價格排序'''
    showFruit()
    sortStandard = input("請選擇(0升序;1降序):")
    if sortStandard == "0":
        sortStandard = True
    elif sortStandard == "1":
        sortStandard = False
    else:
        print("您的輸入有誤,請重新輸入!")
    fruit.sort(key = lambda x:x['price'],reverse = sortStandard)
    showFruit()

def exitSystem():
    '''功能7 退出系統'''
    print("您已經退出水果超市系統")
    exit()

def main():
    notExit = True
    while notExit:
        menu()
        try:
            option = int(input("請選擇功能:"))
        except Exception as e:
            print("請重新輸入")
        if option in [i for i in range(1,8)]:
            if option == 1:
                showFruit()
            elif option == 2:
                searchFruitName()
            elif option == 3:
                addFruit()
            elif option == 4:
                changeFruit()
            elif option == 5:
                delFruit()
            elif option == 6:
                sortFruit()
            elif option == 7:
                notExit = False
                exitSystem()


if __name__ == '__main__':
    main()

class FruitMarket():
    def __init__(self):
        self.fruit = []

    def showFruit(self):
        '''功能1 查詢全部水果'''
        print('-' * 30)
        print("水果的資訊如下:")
        print('-' * 30)
        print('序號 水果名  價格  數量')
        fru_id = 1
        for fru_temp in self.fruit:
            print("%s   %s   %s    %s " % (fru_id, fru_temp['name'], fru_temp['price'], fru_temp['num']))
            fru_id += 1

    def searchFruitName(self):
        '''功能2 查詢指定名稱的水果'''
        self.showFruit()
        fru_name = input("請輸入想要查詢的水果名稱")
        fru_id = 1
        for fru in self.fruit:
            if fru_name in fru['name']:
                print("該水果資訊如下:")
                print("%d   %s  %s    %s " % (fru_id, fru['name'], fru['price'], fru['num']))
                return
            fru_id += 1
        print("沒有查詢到該水果名稱")

    def addFruit(self):
        '''功能3 增加水果(增加到資料庫)'''
        newFruitName = input('請輸入新水果的名稱')
        newFruitPrice = input('請輸入新水果的價格')
        newFruitNum = input('請輸入新水果的數量')

        newFruit = {}
        newFruit['name'] = newFruitName
        newFruit['price'] = newFruitPrice
        newFruit['num'] = newFruitNum

        self.fruit.append(newFruit)

    def changeFruit(self):
        '''功能4 修改水果數量或者價格'''
        self.showFruit()

        fru_id = int(input("請輸入需要修改的水果的序號: "))

        changeFruitName = input('請輸入修改後的水果的名稱')
        changeFruitPrice = input('請輸入修改後的水果的價格')
        changeFruitNum = input('請輸入修改後的水果的數量')

        self.fruit[fru_id - 1]['name'] = changeFruitName
        self.fruit[fru_id - 1]['price'] = changeFruitPrice
        self.fruit[fru_id - 1]['num'] = changeFruitNum

    def delFruit(self):
        '''功能5 刪除水果'''
        self.showFruit()
        delFruitId = int(input('請輸入要刪除的序號:'))
        del self.fruit[delFruitId - 1]

    def sortFruit(self):
        '''功能6 按照價格排序'''
        self.showFruit()
        sortStandard = input("請選擇(0升序;1降序):")
        if sortStandard == "0":
            sortStandard = True
        elif sortStandard == "1":
            sortStandard = False
        else:
            print("您的輸入有誤,請重新輸入!")
        self.fruit.sort(key=lambda x: x['price'], reverse=sortStandard)
        self.showFruit()

    def exitSystem(self):
        '''功能7 退出系統'''
        print("您已經退出水果超市系統")
        exit()
def menu( ):
    print(
        '''
        ********************水果超市********************  (面向物件,面向過程)
                1. 查詢全部水果
                2. 查詢指定名稱的水果
                3. 增加水果(增加到資料庫)
                4. 修改水果數量或者價格
                5. 刪除水果
                6. 按照價格排序
                7. 退出系統
        ***********************************************
        '''
    )

fruitmarket = FruitMarket()

def main():
    notExit = True
    while notExit:
        menu()
        try:
            option = int(input("請選擇功能:"))
        except Exception as e:
            print("請重新輸入")
        if option == 1:
            fruitmarket.showFruit()
        elif option == 2:
            fruitmarket.searchFruitName()
        elif option == 3:
            fruitmarket.addFruit()
        elif option == 4:
            fruitmarket.changeFruit()
        elif option == 5:
            fruitmarket.delFruit()
        elif option == 6:
            fruitmarket.sortFruit()
        elif option == 7:
            notExit = False
            fruitmarket.exitSystem()



if __name__ == '__main__':
    main()

matplotlib基礎彙總_01
灰度化處理就是將一幅色彩影象轉化為灰度影象的過程。彩色影象分為R,G,B三個分量,
分別顯示出紅綠藍等各種顏色,灰度化就是使彩色的R,G,B分量相等的過程。
灰度值大的畫素點比較亮(畫素值最大為255,為白色),反之比較暗(畫素最下為0,為黑色)。 影象灰度化的演算法主要有以下3種:

data2 = data.mean(axis = 2)

data3 = np.dot(data,[0.299,0.587,0.114])
Matplotlib中的基本圖表包括的元素


x軸和y軸
水平和垂直的軸線

x軸和y軸刻度
刻度標示座標軸的分隔,包括最小刻度和最大刻度

x軸和y軸刻度標籤
表示特定座標軸的值

繪圖區域
實際繪圖的區域
繪製一條曲線

x = np.arange(0.0,6.0,0.01)
plt.plot(x, x**2)
plt.show()
繪製多條曲線

x = np.arange(1, 5,0.01)
plt.plot(x, x**2)
plt.plot(x, x**3.0)
plt.plot(x, x*3.0)
plt.show()


x = np.arange(1, 5)
plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
plt.show()
繪製網格線

設定grid引數(引數與plot函式相同)
lw代表linewidth,線的粗細
alpha表示線的明暗程度

# 使用子圖顯示不同網格線對比
fig  = plt.figure(figsize=(20,3))

x = np.linspace(0, 5, 100)

# 使用預設網格設定
ax1 = fig.add_subplot(131)
ax1.plot(x, x**2, x, x**3,lw=2) 
ax1.grid(True) # 顯式網格線

# 對網格線進行設定
ax2 = fig.add_subplot(132)
ax2.plot(x, x**2, x, x**4, lw=2)
ax2.grid(color='r', alpha=0.5, linestyle='dashed', linewidth=0.5) # grid函式中用與plot函式同樣的引數設定網格線
# 對網格線進行設定
ax3 = fig.add_subplot(133)
ax3.plot(x, x**2, x, x**4, lw=2)
ax3.grid(color='r', alpha=0.5, linestyle='-.', linewidth=0.5) # grid函式中用與plot函式同樣的引數設定網格線
座標軸界限 axis 方法

x = np.arange(1, 5)
plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
# plt.axis() # shows the current axis limits values;如果axis方法沒有任何引數,則返回當前座標軸的上下限
# (1.0, 4.0, 0.0, 12.0)
# plt.axis([0, 15, -5, 13]) # set new axes limits;axis方法中有引數,設定座標軸的上下限;引數順序為[xmin, xmax, ymin, ymax]
plt.axis(xmax=5,ymax=23) # 可使用xmax,ymax引數
plt.show()


設定緊湊型座標軸
x = np.arange(1, 5)
plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
plt.axis('tight') # 緊湊型座標軸
plt.show()



plt除了axis方法設定座標軸範圍,還可以通過xlim,ylim設定座標軸範圍
x = np.arange(1, 5)
plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)
plt.xlim([0, 5]) # ylim([ymin, ymax])
plt.ylim([-1, 13]) # xlim([xmin, xmax])
plt.show()
座標軸標籤

plt.plot([1, 3, 2, 4])
plt.xlabel('This is the X axis')
plt.ylabel('This is the Y axis')
plt.show()
座標軸標題

plt.plot([1, 3, 2, 4])
plt.title('Simple plot')
plt.show()
label引數為'_nolegend_',則圖例中不顯示


x = np.arange(1, 5)
plt.plot(x, x*1.5, label = '_nolegend_') # label引數為'_nolegend_',則圖例中不顯示
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend()
plt.show()

圖例 legend

legend方法
兩種傳參方法:


【推薦使用】在plot函式中增加label引數
在legend方法中傳入字串列表

方法一:
x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal') # 在plot函式中增加label引數
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend()
plt.show()

方法二:
x = np.arange(1, 5)
plt.plot(x, x*1.5)
plt.plot(x, x*3.0)
plt.plot(x, x/3.0)
plt.legend(['Normal', 'Fast', 'Slow']) # 在legend方法中傳入字串列表
plt.show()
loc 引數

x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal')
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend(loc=10)
plt.show()

loc引數可以是2元素的元組,表示圖例左下角的座標

x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal')
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend(loc=(0,1)) # loc引數可以是2元素的元組,表示圖例左下角的座標
plt.show()

ncol引數控制圖例中有幾列

x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal')
plt.plot(x, x*3.0, label='Fast')
plt.plot(x, x/3.0, label='Slow')
plt.legend(loc=0, ncol=2) # ncol控制圖例中有幾列
plt.show()

linestyle 屬性

plt.plot(np.random.randn(1000).cumsum(), linestyle = ':',marker = '.', label='one')
plt.plot(np.random.randn(1000).cumsum(), 'r--', label='two') 
plt.plot(np.random.randn(1000).cumsum(), 'b.', label='three')
plt.legend(loc='best') # loc='best'
plt.show()

儲存圖片

filename
含有檔案路徑的字串或Python的檔案型物件。影象格式由副檔名推斷得出,例如,.pdf推斷出PDF,.png推斷出PNG (“png”、“pdf”、“svg”、“ps”、“eps”……)
dpi
影象解析度(每英寸點數),預設為100
facecolor
影象的背景色,預設為“w”(白色)


x = np.random.randn(1000).cumsum()
fig = plt.figure(figsize = (10,3))

splt = fig.add_subplot(111)
splt.plot(x)

fig.savefig(filename = "filena.eps",dpi = 100,facecolor = 'g') 

matplotlib基礎彙總_02
設定plot的風格和樣式
點和線的樣式
顏色

引數color或c

五種定義顏色值的方式

別名
color='r'

合法的HTML顏色名
color = 'red'

HTML十六進位制字串
color = '#eeefff'

歸一化到[0, 1]的RGB元組
color = (0.3, 0.3, 0.4)

灰度
color = (0.1)

透明度

y = np.arange(1, 3)
plt.plot(y, c="red", alpha=0.1);    # 設定透明度
plt.plot(y+1, c="red", alpha=0.5);
plt.plot(y+2, c="red", alpha=0.9);
設定背景色
通過plt.subplot()方法傳入facecolor引數,來設定座標軸的背景色

plt.subplot(facecolor='orange');
plt.plot(np.random.randn(10),np.arange(1,11))


線型

不同寬度破折線

# 第一段線2個點的寬度,接下來的空白區5個點的寬度,第二段線5個點的寬度,空白區2個點的寬度,以此類推
plt.plot(np.linspace(-np.pi, np.pi, 256, endpoint=True),
         np.cos(np.linspace(-np.pi, np.pi, 256, endpoint=True)), 
         dashes=[2, 5, 5, 2]);

點型 

y = np.arange(1, 3, 0.2)
plt.plot(y, '1', y+0.5, '2', y+1, '3', y+1.5,'4');
plt.plot(y+2, '3') #不宣告marker,預設ls = None
plt.plot(y+2.5,marker = '3') #聲明瞭marker,ls 預設是實線
plt.show()

多引數連用

顏色、點型、線型

x = np.linspace(0, 5, 10)
plt.plot(x,3*x,'r-.')
plt.plot(x, x**2, 'b^:') # blue line with dots
plt.plot(x, x**3, 'go-.') # green dashed line
plt.show()

更多點和線的設定

y = np.arange(1, 3, 0.3)
plt.plot(y, color='blue', 
         linestyle='dashdot', 
         linewidth=4, marker='o',
         markerfacecolor='red', 
         markeredgecolor='black', 
         markeredgewidth=3, 
         markersize=12);
plt.show()

在一條語句中為多個曲線進行設定

多個曲線同一設定¶
plt.plot(x1, y1, x2, y2, fmt, ...)


多個曲線不同設定¶
plt.plot(x1, y1, fmt1, x2, y2, fmt2, ...)

在一條語句中為多個曲線進行設定


多個曲線同一設定¶
plt.plot(x1, y1, x2, y2, fmt, ...)


多個曲線不同設定¶
plt.plot(x1, y1, fmt1, x2, y2, fmt2, ...)
三種設定方式

向方法傳入關鍵字引數


對例項使用一系列的setter方法

x = np.arange(0,10)
y = np.random.randint(10,30,size = 10)
line,= plt.plot(x, y)
line2 = plt.plot(x,y*2,x,y*3)
line.set_linewidth(5)
line2[1].set_marker('o')
print(line,line2)


使用setp()方法
line = plt.plot(x, y)
plt.setp(line, 'linewidth', 1.5,'color','r','marker','o','linestyle','--')
X、Y軸座標刻度
xticks()和yticks()方法

x = [5, 3, 7, 2, 4, 1]
plt.plot(x);
plt.xticks(range(len(x)), ['a', 'b', 'c', 'd', 'e', 'f']); # 傳入位置和標籤引數,以修改座標軸刻度
plt.yticks(range(1, 8, 2));
plt.show()

面向物件方法

set_xticks、set_yticks、set_xticklabels、set_yticklabels方法


fig = plt.figure(figsize=(10, 4))
ax = fig.add_subplot(111)

x = np.linspace(0, 5, 100)

ax.plot(x, x**2, x, x**3, lw=2)

ax.set_xticks([1, 2, 3, 4, 5])
ax.set_xticklabels(['a','b','c','d','e'], fontsize=18)

yticks = [0, 50, 100, 150]
ax.set_yticks(yticks)
ax.set_yticklabels([y for y in yticks], fontsize=18); # use LaTeX formatted labels

正弦餘弦:LaTex語法,用$\pi$等表示式在圖表上寫上希臘字母

x = np.arange(-np.pi,np.pi,0.01)
plt.figure(figsize=(12,9))
plt.plot(x,np.sin(x),x,np.cos(x))

plt.axis([x.min()-1,x.max()+1,-1.2,1.2])

#xticks:引數一刻度,引數二,對應刻度上的值
plt.xticks(np.arange(-np.pi,np.pi+1,np.pi/2),
           ['$-\delta$','$-\pi$/2','0','$\pi$/2','$\pi$'],size = 20)

plt.yticks([-1,0,1],['min','0','max'],size = 20)

plt.show() 


matplotlib基礎彙總_03
四圖
直方圖

【直方圖的引數只有一個x!!!不像條形圖需要傳入x,y】
hist()的引數
bins
可以是一個bin數量的整數值,也可以是表示bin的一個序列。預設值為10
normed
如果值為True,直方圖的值將進行歸一化處理,形成概率密度,預設值為False
color
指定直方圖的顏色。可以是單一顏色值或顏色的序列。如果指定了多個數據集合,顏色序列將會設定為相同的順序。如果未指定,將會使用一個預設的線條顏色
orientation
通過設定orientation為horizontal建立水平直方圖。預設值為vertical


x = np.random.randint(5,size = 5)
display(x)
plt.hist(x,histtype = 'bar'); # 預設繪製10個bin
plt.show()
普通直方圖/累計直方圖

n = np.random.randn(10000)

fig,axes = plt.subplots(1,2,figsize = (12,4))
axes[0].hist(n,bins = 50)#普通直方圖
axes[0].set_title('Default histogram')
axes[0].set_xlim(min(n),max(n))

axes[1].hist(n,bins = 50,cumulative = True)# 累計直方圖
axes[1].set_title('Cumulative detailed histogram')
axes[1].set_xlim(min(n),max(n))

正太分佈

u = 100 #數學期望
s = 15 #方差
x = np.random.normal(u,s,1000) # 生成正太分佈資料

ax = plt.gca() #獲取當前圖表
ax.set_xlabel('Value')
ax.set_ylabel('Frequency') #設定x,y軸標題

ax.set_title("Histogram normal u = 100 s = 15") #設定圖表標題

ax.hist(x,bins = 100,color = 'r',orientation='horizontal')
plt.show()

條形圖
bar 

# 第一個引數為條形左下角的x軸座標,第二個引數為條形的高度;
# matplotlib會自動設定條形的寬度,本例中條形寬0.8
plt.bar([1, 2, 3], [3, 2, 5]); 
plt.show()
# width引數設定條形寬度;color引數設定條形顏色;bottom引數設定條形底部的垂直座標
plt.bar([1, 2, 3], [3, 2, 5], width=0.5, color='r', bottom=1);
plt.ylim([0, 7])
plt.show()

# 例子:繪製並列條形圖

data1 = 10*np.random.rand(5)
data2 = 10*np.random.rand(5)
data3 = 10*np.random.rand(5)

locs = np.arange(1, len(data1)+1)
width = 0.27

plt.bar(locs, data1, width=width);
plt.bar(locs+width, data2, width=width, color='red');
plt.bar(locs+2*width, data3, width=width, color='green') ;
plt.xticks(locs + width*1, locs);
plt.show()

barh

plt.barh([1, 2, 3], [3, 2, 5],height = 0.27,color = 'yellow');
plt.show()

餅圖
【餅圖也只有一個引數x!】
pie()
餅圖適合展示各部分佔總體的比例,條形圖適合比較各部分的大小
plt.figure(figsize = (4,4)) # 餅圖繪製正方形
x = [45,35,20] #百分比
labels = ['Cats','Dogs','Fishes'] #每個區域名稱
plt.pie(x,labels = labels)
plt.show()

plt.figure(figsize=(4, 4));
x = [0.1, 0.2, 0.3] # 當各部分之和小於1時,則不計算各部分佔總體的比例,餅的大小是數值和1之比
labels = ['Cats', 'Dogs', 'Fishes']
plt.pie(x, labels=labels); # labels引數可以設定各區域標籤
plt.show()

# labels引數設定每一塊的標籤;labeldistance引數設定標籤距離圓心的距離(比例值)
# autopct引數設定比例值的顯示格式(%1.1f%%);pctdistance引數設定比例值文字距離圓心的距離
# explode引數設定每一塊頂點距圓形的長度(比例值);colors引數設定每一塊的顏色;
# shadow引數為布林值,設定是否繪製陰影

plt.figure(figsize=(4, 4));
x = [4, 9, 21, 55, 30, 18]
labels = ['Swiss', 'Austria', 'Spain', 'Italy', 'France', 'Benelux']
explode = [0.2, 0.1, 0, 0, 0.1, 0]
colors = ['r', 'k', 'b', 'm', 'c', 'g']
plt.pie(x, 
        labels=labels, 
        labeldistance=1.2,
        explode=explode, 
        colors=colors, 
        autopct='%1.1f%%', 
        pctdistance=0.5, 
        shadow=True);
plt.show()

散點圖
【散點圖需要兩個引數x,y,但此時x不是表示x軸的刻度,而是每個點的橫座標!】
scatter()
# s引數設定散點的大小;c引數設定散點的顏色;marker引數設定散點的形狀
x = np.random.randn(1000)
y = np.random.randn(1000)
size = 50*abs(np.random.randn(1000))
colors = np.random.randint(16777215,size = 1000)


li = []
for color in colors:
    a = hex(color)
    str1 = a[2:]
    l = len(str1)
    for i in range(1,7-l):
        str1 = '0'+str1
    str1 = "#" + str1
    li.append(str1)

plt.scatter(x, y,s = size, c=li, marker='d');
plt.show()

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

import matplotlib.pyplot as plt

x = np.random.randn(1000)

y1 = np.random.randn(1000)
y2 = 1.2 + np.exp(x) #exp(x) 返回的是e的x次方

ax1 = plt.subplot(121)
plt.scatter(x,y1,color = 'purple',alpha = 0.3,edgecolors = 'white',label = 'no correl')
plt.xlabel('no correlation')
plt.grid(True)
plt.legend()


ax2 = plt.subplot(122)
plt.scatter(x,y2,color = 'green',alpha = 0.3,edgecolors = 'gray',label = 'correl')
plt.xlabel('correlation')
plt.grid(True)
plt.legend()

plt.show()

圖形內的文字、註釋、箭頭
文字

x = np.arange(0, 7, .01)
y = np.sin(x)
plt.plot(x, y);
plt.text(0.1, -0.04, 'sin(0)=0'); # 位置引數是座標
plt.show()

註釋


# xy引數設定箭頭指示的位置,xytext引數設定註釋文字的位置
# arrowprops引數以字典的形式設定箭頭的樣式
# width引數設定箭頭長方形部分的寬度,headlength引數設定箭頭尖端的長度,
# headwidth引數設定箭頭尖端底部的寬度,shrink引數設定箭頭頂點、尾部與指示點、註釋文字的距離(比例值)

y = [13, 11, 13, 12, 13, 10, 30, 12, 11, 13, 12, 12, 12, 11, 12]
plt.plot(y);
plt.ylim(ymax=35); # 為了讓註釋不會超出圖的範圍,需要調整y座標軸的界限
plt.annotate('this spot must really\nmean something', xy=(6, 30), xytext=(8, 31.5),
             arrowprops=dict(width=15, headlength=20, headwidth=20, facecolor='black', shrink=0.1));
plt.show()

# 生成3個正態分佈資料資料集
x1 = np.random.normal(30, 3, 100)
x2 = np.random.normal(20, 2, 100)
x3 = np.random.normal(10, 3, 100)

# 繪製3個數據集,併為每個plot指定一個字串標籤
plt.plot(x1, label='plot') # 如果不想在圖例中顯示標籤,可以將標籤設定為_nolegend_
plt.plot(x2, label='2nd plot')
plt.plot(x3, label='last plot')

# 繪製圖例
plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.102), # 指定邊界框起始位置為(0, 1.02),並設定寬度為1,高度為0.102
           ncol=3, # 設定列數為3,預設值為1
           mode="expand", # mode為None或者expand,當為expand時,圖例框會擴充套件至整個座標軸區域
           borderaxespad=0.) # 指定座標軸和圖例邊界之間的間距

# 繪製註解
plt.annotate("Important value", # 註解文字的內容
             xy=(55,20), # 箭頭終點所在位置
             xytext=(5, 38), # 註解文字的起始位置,箭頭由xytext指向xy座標位置
             arrowprops=dict(arrowstyle='->')); # arrowprops字典定義箭頭屬性,此處用arrowstyle定義箭頭風格

箭頭


matplotlib基礎彙總_04
3D圖形
導包


import numpy as np
import matplotlib.pyplot as plt
#3d圖形必須的
from mpl_toolkits.mplot3d.axes3d import Axes3D
%matplotlib inline
生成資料


#係數,由X,Y生成Z
a = 0.7
b =  np.pi 

#計算Z軸的值
def mk_Z(X, Y):
    return 2 + a - 2 * np.cos(X) * np.cos(Y) - a * np.cos(b - 2*X)

#生成X,Y,Z
x = np.linspace(0, 2*np.pi, 100)
y = np.linspace(0, 2*np.pi, 100)
X,Y = np.meshgrid(x, y)
Z = mk_Z(X, Y)
繪製圖形

fig = plt.figure(figsize=(14,6))

#建立3d的檢視,使用屬性projection
ax = fig.add_subplot(1, 2, 1, projection='3d')

ax.plot_surface(X,Y,Z,rstride = 5,cstride = 5)

#建立3d檢視,使用colorbar,新增顏色柱
ax = fig.add_subplot(1, 2, 2, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap='rainbow', antialiased=True)
cb = fig.colorbar(p, shrink=0.5)

玫瑰圖
#極座標條形圖
def showRose(values,title):
    
    max_value = values.max()
    # 分為8個面元
    N = 8
    # 面元的分隔角度
    angle = np.arange(0.,2 * np.pi, 2 * np.pi / N)
    # 每個面元的大小(半徑)
    radius = np.array(values)
    # 設定極座標條形圖
    
    plt.axes([0, 0, 2, 2], polar=True,facecolor = 'g')
    
    colors = [(1 - x/max_value, 1 - x/max_value, 0.75) for x in radius]
    # 畫圖
    
    plt.bar(angle, radius, width=(2*np.pi/N), bottom=0.0, color=colors)
    plt.title(title,x=0.2, fontsize=20)
繪製圖形

#拉韋納(Ravenna)又譯“臘萬納”“拉文納”“拉溫拿”。義大利北部城市。位於距亞得里亞海10公里的沿海平原上


data = np.load('Ravenna_wind.npy')
hist, angle = np.histogram(data,8,[0,360])
showRose(hist,'Ravenna')

城市氣候與海洋關係
導包

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import Series,DataFrame
%matplotlib inline
載入資料

#義大利小鎮費拉拉
ferrara1 = pd.read_csv('./ferrara_150715.csv')
ferrara2 = pd.read_csv('./ferrara_250715.csv')
ferrara3 = pd.read_csv('./ferrara_270615.csv')
ferrara = pd.concat([ferrara1,ferrara2,ferrara3],ignore_index=True) 
去除沒用的列

asti.drop(['Unnamed: 0'],axis = 1,inplace=True)

bologna.drop(['Unnamed: 0'],axis = 1,inplace=True)

cesena.drop(['Unnamed: 0'],axis = 1,inplace=True)

ferrara.drop(['Unnamed: 0'],axis = 1,inplace=True)

mantova.drop(['Unnamed: 0'],axis = 1,inplace=True)

milano.drop(['Unnamed: 0'],axis = 1,inplace=True)

piacenza.drop(['Unnamed: 0'],axis = 1,inplace=True)

ravenna.drop(['Unnamed: 0'],axis = 1,inplace=True)

torino.drop(['Unnamed: 0'],axis = 1,inplace=True)
獲取個城市距離海邊距離,最高溫度,最低溫度,最高溼度,最低溼度


dist = [ravenna['dist'][0],
     cesena['dist'][0],
     faenza['dist'][0],
     ferrara['dist'][0],
     bologna['dist'][0],
     mantova['dist'][0],
     piacenza['dist'][0],
     milano['dist'][0],
     asti['dist'][0],
     torino['dist'][0]
]
temp_max = [ravenna['temp'].max(),
     cesena['temp'].max(),
     faenza['temp'].max(),
     ferrara['temp'].max(),
     bologna['temp'].max(),
     mantova['temp'].max(),
     piacenza['temp'].max(),
     milano['temp'].max(),
     asti['temp'].max(),
     torino['temp'].max()
]
temp_min = [ravenna['temp'].min(),
     cesena['temp'].min(),
     faenza['temp'].min(),
     ferrara['temp'].min(),
     bologna['temp'].min(),
     mantova['temp'].min(),
     piacenza['temp'].min(),
     milano['temp'].min(),
     asti['temp'].min(),
     torino['temp'].min()
]
hum_min = [ravenna['humidity'].min(),
     cesena['humidity'].min(),
     faenza['humidity'].min(),
     ferrara['humidity'].min(),
     bologna['humidity'].min(),
     mantova['humidity'].min(),
     piacenza['humidity'].min(),
     milano['humidity'].min(),
     asti['humidity'].min(),
     torino['humidity'].min()
]
hum_max = [ravenna['humidity'].max(),
     cesena['humidity'].max(),
     faenza['humidity'].max(),
     ferrara['humidity'].max(),
     bologna['humidity'].max(),
     mantova['humidity'].max(),
     piacenza['humidity'].max(),
     milano['humidity'].max(),
     asti['humidity'].max(),
     torino['humidity'].max()
]
顯示最高溫度與離海遠近的關係

plt.axis([0,400,32,35])
plt.plot(dist,temp_max,'ro')

根據距海遠近劃分資料


觀察發現,離海近的可以形成一條直線,離海遠的也能形成一條直線。
首先使用numpy:把列表轉換為numpy陣列,用於後續計算。
分別以100公里和50公里為分界點,劃分為離海近和離海遠的兩組資料

# 把列表轉換為numpy陣列
x = np.array(dist)
display('x:',x)
y = np.array(temp_max)
display('y:',y)

# 離海近的一組資料
x1 = x[x<100]
x1 = x1.reshape((x1.size,1))
display('x1:',x1)
y1 = y[x<100]
display('y1:',y1)

# 離海遠的一組資料
x2 = x[x>50]
x2 = x2.reshape((x2.size,1))
display('x2:',x2)
y2 = y[x>50]
display('y2:',y2)
機器學習計算迴歸模型


from sklearn.svm import SVR
svr_lin1 = SVR(kernel='linear', C=1e3)
svr_lin2 = SVR(kernel='linear', C=1e3)
svr_lin1.fit(x1, y1)
svr_lin2.fit(x2, y2)
xp1 = np.arange(10,100,10).reshape((9,1))
xp2 = np.arange(50,400,50).reshape((7,1))
yp1 = svr_lin1.predict(xp1)
yp2 = svr_lin2.predict(xp2)
繪製迴歸曲線


plt.plot(xp1, yp1, c='r', label='Strong sea effect')
plt.plot(xp2, yp2, c='b', label='Light sea effect')
#plt.axis('tight')
plt.legend()
plt.scatter(x, y, c='k', label='data')

最低溫度與海洋距離關係

plt.axis((0,400,16,21))
plt.plot(dist,temp_min,'bo')

最低溼度與海洋距離關係


plt.axis([0,400,70,120])
plt.plot(dist,hum_min,'bo')
最高溼度與海洋距離關係

plt.axis([0,400,70,120])
plt.plot(dist,hum_max,'bo')
平均溼度與海洋距離的關係

hum_mean = [ravenna['humidity'].mean(),
     cesena['humidity'].mean(),
     faenza['humidity'].mean(),
     ferrara['humidity'].mean(),
     bologna['humidity'].mean(),
     mantova['humidity'].mean(),
     piacenza['humidity'].mean(),
     milano['humidity'].mean(),
     asti['humidity'].mean(),
     torino['humidity'].mean()
]
plt.plot(dist,hum_mean,'bo')
風速與風向的關係

plt.plot(ravenna['wind_deg'],ravenna['wind_speed'],'ro')
在子圖中,同時比較風向與溼度和風力的關係

plt.subplot(211)
plt.plot(cesena['wind_deg'],cesena['humidity'],'bo')
plt.subplot(212)
plt.plot(cesena['wind_deg'],cesena['wind_speed'],'bo')
玫瑰圖

def showRoseWind(values,city_name):
    '''
    查看風向圖,半徑越大,代表這個方向上的風越多
    '''
    max_value = values.max()
    # 分為8個面元
    N = 8
    # 面元的分隔角度
    theta = np.arange(0.,2 * np.pi, 2 * np.pi / N)
    # 每個面元的大小(半徑)
    radii = np.array(values)
    # 設定極座標條形圖
    plt.axes([0.025, 0.025, 0.95, 0.95], polar=True)
    colors = [(1 - x/max_value, 1 - x/max_value, 0.75) for x in radii]
    # 畫圖
    plt.bar(theta, radii, width=(2*np.pi/N), bottom=0.0, color=colors)
    plt.title(city_name,x=0.2, fontsize=20)
用numpy建立一個直方圖,將360度劃分為8個面元,將資料分類到這8個面元中


hist, bin = np.histogram(ravenna['wind_deg'],8,[0,360])
print(hist)
hist = hist/hist.sum()
print(bin)
showRoseWind(hist,'Ravenna')

計算米蘭各個方向的風速

print(milano[milano['wind_deg']<45]['wind_speed'].mean())
print(milano[(milano['wind_deg']>44) & (milano['wind_deg']<90)]['wind_speed'].mean())
print(milano[(milano['wind_deg']>89) & (milano['wind_deg']<135)]['wind_speed'].mean())
print(milano[(milano['wind_deg']>134) & (milano['wind_deg']<180)]['wind_speed'].mean())
print(milano[(milano['wind_deg']>179) & (milano['wind_deg']<225)]['wind_speed'].mean())
print(milano[(milano['wind_deg']>224) & (milano['wind_deg']<270)]['wind_speed'].mean())
print(milano[(milano['wind_deg']>269) & (milano['wind_deg']<315)]['wind_speed'].mean())
print(milano[milano['wind_deg']>314]['wind_speed'].mean())
將各個方向風速儲存到列表中

degs = np.arange(45,361,45)
tmp =  []
for deg in degs:
    tmp.append(milano[(milano['wind_deg']>(deg-46)) & (milano['wind_deg']<deg)]['wind_speed'].mean())
speeds = np.array(tmp)
print(speeds)
畫出各個方向的風速

N = 8
theta = np.arange(0.,2 * np.pi, 2 * np.pi / N)
radii = np.array(speeds)
plt.axes([0.025, 0.025, 0.95, 0.95], polar=True)
colors = [(1-x/10.0, 1-x/10.0, 0.75) for x in radii]
bars = plt.bar(theta, radii, width=(2*np.pi/N), bottom=0.0, color=colors)
plt.title('Milano',x=0.2, fontsize=20)

抽取函式

def RoseWind_Speed(city):
   degs = np.arange(45,361,45)
   tmp =  []
   for deg in degs:
      tmp.append(city[(city['wind_deg']>(deg-46)) & (city['wind_deg']<deg)]['wind_speed'].mean())
   return np.array(tmp)


def showRoseWind_Speed(speeds,city_name):
   N = 8
   theta = np.arange(0.,2 * np.pi, 2 * np.pi / N)
   radii = np.array(speeds)
   plt.axes([0.025, 0.025, 0.95, 0.95], polar=True)
   colors = [(1-x/10.0, 1-x/10.0, 0.75) for x in radii]
   bars = plt.bar(theta, radii, width=(2*np.pi/N), bottom=0.0, color=colors)
   plt.title(city_name,x=0.2, fontsize=20)
函式呼叫

showRoseWind_Speed(RoseWind_Speed(ravenna),'Ravenna')


根據列表的值來顯示每一個元素出現的次數
lst = ['中雨','雷陣雨','中到大雨','','多雲','','中雨']
dic = {}

for i in lst:
    if i not in dic:
        dic[i] = lst.count(i)

print(dic)

鑽石和玻璃球遊戲(鑽石位置固定)

'''
開始,你可以隨意選擇一個抽屜,在開啟它之前,
主持人會開啟另外一個抽屜,露出抽屜裡的玻璃球。
這時,主持人會給你一次更換自己選擇的機會。
請自己認真分析一下“不換選擇能有更高的機率獲得鑽石,
還是換選擇能有更高的機率獲得鑽石?或機率沒有發生變化?”寫出你分析的思路和結果。
設法編寫python程式驗證自己的想法,
驗證的結果支援了你的分析結果,還是沒有支援你的分析結果,
請寫出結果,並附上你的程式程式碼,並在程式程式碼中通過註釋說明你解決問題的思路。
(提示:可以藉助隨機數函式完成此程式)
'''
import random
print("鑽石和玻璃球的遊戲開始了")
# 擺在你面前有3個關閉的抽屜
lst_dic = [{'抽屜':'鑽石'},{'抽屜':'玻璃球'},{'抽屜':'玻璃球'}]

# 定義鑽石
zs = 0
# 定義玻璃球
blq = 0

def Game(your_choice,lst_dic):

    isLouchu = False
    # 檢視主持人是否露出
    for num in range(len(lst_dic)):
        if not isLouchu:
            if lst_dic[your_choice]['抽屜'] == '鑽石':
                # 第一種 抽到 鑽石
                if num != your_choice:
                    print("主持人露出了 %d 號抽屜的玻璃球"%(num + 1))
                    isLouchu = True
            else:
                # 第二種 抽到 玻璃球
                if num != your_choice and lst_dic[num]['抽屜'] != '鑽石':
                    print("主持人露出了 %d 號抽屜的玻璃球"%(num + 1))
                    isLouchu = True

    choice = 'yn'
    you_select = random.choice(choice)
    if you_select == 'y':
        lst_nums = [0,1,2]
        ischoose = False
        for new_choice in lst_nums:
            if not ischoose :
                if (new_choice != num) and (new_choice != your_choice):
                    print("你新的選擇是:",new_choice+1,"號抽屜")
                    your_choice = new_choice

                    ischoose = True

        ChooseLater(your_choice)


    else:
        print("不變選擇,繼續堅持我的 %d 號抽屜"%(your_choice + 1))
        your_choice = your_choice
        ChooseLater(your_choice)

def ChooseLater(your_choice):
    # 選擇後進行計數  公佈答案
    global zs, blq
    if lst_dic[your_choice]['抽屜'] == '鑽石':
        zs += 1
        # 鑽石數 +1
    else:
        blq += 1
        # 玻璃球數 +1
    answer_num = 0
    isanswer = False
    for answer in lst_dic:
        if not isanswer:
            if answer['抽屜'] == '鑽石':
                print("鑽石在 %d 號抽屜 "%(answer_num + 1))
                isanswer = True
        answer_num += 1

nums = int(input("請輸入想要實驗的次數"))
for i in range(nums):
    # 你可以隨意選擇一個抽屜
    your_choice = random.randint(0, 2)
    print("你當前想要選擇的是 %d 號抽屜" % (your_choice + 1))
    Game(your_choice,lst_dic)

print("抽到的鑽石數為: %d"%(zs))

print("抽到的玻璃球數為: %d"%(blq))

print("鑽石的概率是 %.2f"%(zs/nums))

小人推心圖(網上程式碼)
from turtle import *

def go_to(x, y):
    up()
    goto(x, y)
    down()


def head(x, y, r):
    go_to(x, y)
    speed(1)
    circle(r)
    leg(x, y)


def leg(x, y):
    right(90)
    forward(180)
    right(30)
    forward(100)
    left(120)
    go_to(x, y - 180)
    forward(100)
    right(120)
    forward(100)
    left(120)
    hand(x, y)


def hand(x, y):
    go_to(x, y - 60)
    forward(100)
    left(60)
    forward(100)
    go_to(x, y - 90)
    right(60)
    forward(100)
    right(60)
    forward(100)
    left(60)
    eye(x, y)


def eye(x, y):
    go_to(x - 50, y + 130)
    right(90)
    forward(50)
    go_to(x + 40, y + 130)
    forward(50)
    left(90)


def big_Circle(size):
    speed(20)
    for i in range(150):
        forward(size)
        right(0.3)


def line(size):
    speed(1)
    forward(51 * size)


def small_Circle(size):
    speed(10)
    for i in range(210):
        forward(size)
        right(0.786)


def heart(x, y, size):
    go_to(x, y)
    left(150)
    begin_fill()
    line(size)
    big_Circle(size)
    small_Circle(size)
    left(120)
    small_Circle(size)
    big_Circle(size)
    line(size)
    end_fill()


def main():
    pensize(2)
    color('red', 'pink')
    head(-120, 100, 100)
    heart(250, -80, 1)
    go_to(200, -300)
    write("To: Hany", move=True, align="left", font=("楷體", 20, "normal"))
    done()

main()


0525習題
for i in range(1000,2201):
    if i % 7 == 0 and i % 5 != 0:
        print(i,end = " ")

def func(num):
    if num == 0:
        return 1

    return num * func(num - 1)
print(func(5))

for i in range(100,1000):
    a = i//100
    b = i//10 % 10
    c = i%100%10
    if a**3 + b**3 + c**3 == i:
        print(i)

name = 'seven'
passwd = '123'
num = 3
while num:
    input_name = input("請輸入使用者名稱")
    input_passwd = input("請輸入密碼")
    if input_name == name and input_passwd == passwd:
        print("登陸成功")
        break
    else:
        print("登陸失敗")
    num = num - 1

x,y=eval(input("請輸入兩個數字,逗號分隔:"))
lst_num=[]
for i in range(x):
    L=[]
    for j in range(y):
        L.append(j*i)
    lst_num.append(L)
print(lst_num)

def rank(score):
    if isinstance(score,int):
        if 90 <= score <= 100:
            print("優秀")
        elif 80<= score <= 89:
            print("良好")
        elif 60<= score <= 79:
            print("及格")
        elif 0<= score <= 59:
            print("不及格")
        else:
            print("輸入有誤!")
try:
    score = eval(input("請輸入一個學生的成績"))
    rank(score)
except Exception as e:
    print("請輸入數字")

def test(name):
    if name == 'exit':
        print('歡迎下次使用')
    if name[0].isalpha() or name[0] == '_':
        for i in name[1:]:
            if not (i.isalnum() or i == '_'):
                print('變數名不合法')
                break
        else:
            print('變數名合法!')
    else:
        print('變數名非法!')

name = input()
test(name)

def comb(n,m):
    if(n == m or (not m)):
        return 1
    else:
        return comb(n-1,m) + comb(n-1,m-1)


try:
    n,m = eval(input())
    print(comb(n,m))
except :
    print("輸入有誤!")

def sort(dct):
    newDct={}
    items = list(dct.items())
    items.sort(key=lambda x:x[1],reverse=True)
    for i in range(len(dct)):
        name,score = items[i]
        newDct[name] = score
        print("第%d名:%s,成績: %.2f分"%(i+1,name,newDct[name]))

def avg(dct):
    scores = list(dct.values())
    print("最高分:%.2f"%(max(scores)),end = "")
    print("最低分:%.2f" % (min(scores)),end="")
    print("平均分:%.2f" % (sum(scores) / len(scores)),end="")

dct={}
dct['張三'],dct['李四'],dct['王五'],dct['趙六'],dct['侯七']=eval(input())
sort(dct)
avg(dct)

words = "Python"
print("{:#^9}".format(words))

string = "Python"
if "p" in string:
    print(string[:-1])
else:
    print(string[0:4])

# 建立檔案data.txt,共100000行,每行存放一個1~100之間的整數
import random
f = open('data.txt','w+')
for i in range(100000):
    f.write(str(random.randint(1,100)) + '\n')
f.seek(0,0)
print(f.read())
f.close()

# 生成100個MAC地址並寫入檔案中,MAC地址前6位(16進位制)為01-AF-3B
# 01-AF-3B(-xx)(-xx)(-xx)
# -xx
# 01-AF-3B-xx
# -xx
# 01-AF-3B-xx-xx
# -xx
# 01-AF-3B-xx-xx-xx


import random
import string

def create_mac():
    mac = '01-AF-3B'
    # 生成16進位制的數
    hex_num = string.hexdigits
    for i in range(3):
        # 從16進位制字串中隨機選擇兩個數字
        # 返回值是一個列表
        n = random.sample(hex_num,2)
        # 拼接內容 將小寫字母轉換稱大寫字母
        sn = '-' + ''.join(n).upper()
        mac += sn
    return mac

# 主函式 隨機生成100個mac地址
def main():
    with open('mac.txt','w') as f:
        for i in range(100):
            mac = create_mac()
            print(mac)
            f.write(mac + '\n')
main()

# 生成一個大檔案ips.txt,要求1200行,每行隨機為172.25.254.0/24段的ip
# 讀取ips.txt檔案統計這個檔案中ip出現頻率排前10的ip

import random
def create_ip(filename):
    ip=['172.25.254.'+str(i) for i in range(1,255)]
    with open(filename,'w') as f:
        for i in range(1200):
            f.write(random.sample(ip,1)[0]+'\n')
create_ip('ips.txt')

ips_dict={}

with open('ips.txt') as f :
    for ip in f:
        ip=ip.strip()
        if ip in ips_dict:
            ips_dict[ip]+=1
        else:
            ips_dict[ip]=1

sorted_ip=sorted(ips_dict.items(),key=lambda x:x[1],reverse=True)[:10]
print(sorted_ip)

jieba嚐鮮
import jieba
strings = '我工作在安徽的安徽師範大學,這個大學很美麗,在蕪湖'
# print(dir(jieba))
dic_strings = {}
lst_strings = jieba.lcut(strings)
for ci in lst_strings:
    # 對得到的分詞進行彙總
    dic_strings[ci] = lst_strings.count(ci)
    # 更改字典中單詞出現的次數
print(dic_strings)
inf  無窮
inf = float('inf')

讀取檔案進行繪圖
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

cqlq=pd.read_csv("cqlq.txt",sep="\s+",encoding="gbk")
dxnt=pd.read_csv("dxnt.txt",sep="\s+",encoding="gbk")
ggdq=pd.read_csv("ggdq.txt",sep="\s+",encoding="gbk")
giyy=pd.read_csv("gjyy.txt",sep="\s+",encoding="gbk")



cqlq.columns = ["date","oppr","hipr","lopr","clpr","TR"]
dxnt.columns = ["date","oppr","hipr","lopr","clpr"]
ggdq.columns = ["date","oppr","hipr","lopr","clpr","TR"]
giyy.columns = ["date","oppr","hipr","lopr","clpr","TR"]

a=cqlq
b=dxnt
c=ggdq
d=giyy

ua=(a["clpr"]-a["clpr"].shift(1))/a["clpr"]
ub=(b["clpr"]-b["clpr"].shift(1))/b["clpr"]
uc=(c["clpr"]-c["clpr"].shift(1))/c["clpr"]
ud=(d["clpr"]-d["clpr"].shift(1))/d["clpr"]

u=pd.concat([ua,ub,uc,ud],axis=1)
u.dropna()
miu=u.mean()+0.005
jz=u.cov()
yi = np.ones(4)

miu= np.mat(miu)
jz = np.mat(jz)
yi = np.mat(yi)
nijz = jz.I

a = miu*nijz*miu.T
b =yi*nijz*miu.T
c = yi*nijz*yi.T
deta=a*c-b**2


stock_y=[i*0.0001 for i in range(100)]
stock_x=[(np.sqrt(( c/deta)*(rp-b/c)**2+1/c)).max() for rp in stock_y]

plt.rcParams['font.sans-serif']=['SimHei']
plt.plot(stock_x,stock_y)
plt.xlabel("方差")
plt.ylabel("期望")
print(miu)
print(jz)

plt.show()

 

 


Sqlite3 實現學生資訊增刪改查

import sqlite3
conn = sqlite3.connect('studentsdb.db')
# 連線資料庫
cursor = conn.cursor( )
# 建立資料表

def createDatabase():
    '''建立一個數據表'''
    sql = 'create table student(stuId int primary key,stuName text,stuAge text,stuGender text,stuClass text)'
    cursor.execute(sql)
    conn.commit()

def addInfo(sql = ''):
    '''新增資料'''
    if sql =='':
        # 如果是初始化,則預設會進行增加 6 條資料
        stuInfo = [(1001, '小華', '20', '', '二班'),
                    (1002, '小明', '19', '', '二班'),
                    (1003, '小李', '20', '', '一班'),
                    (1004, '小王', '18', '', '一班'),
                    (1005, '小劉', '20', '', '二班'),
                    (1006, '小張', '19', '', '一班')]
        cursor.executemany("insert into student values(?,?,?,?,?)",stuInfo)
        # 插入多條語句
        conn.commit()


def deleteInfo():
    '''刪除資料'''
    cursor.execute("delete from student where stuId = 1005")
    # 將學號為 1005 的小劉同學刪除
    conn.commit()

def modifyInfo():
    '''修改資料'''
    sql = "update student set stuAge = ? where stuId = ?"
    cursor.execute(sql,(20,1006))
    # 將小張的年齡修改為 20
    conn.commit()

def selectInfo():
    '''查詢學生資訊'''
    sql = 'select * from student'
    # 查詢全部資料
    cursor.execute(sql)
    print(cursor.fetchall())



def main():
    # 建立一個數據表
    createDatabase()
    # 新增資料
    print("新增六條學生資料之後")
    addInfo()
    selectInfo()
    # 修改資料
    print("將小張的年齡修改為 20")
    modifyInfo()
    selectInfo()
    # 刪除資料
    print("將學號為 1005 的小劉同學刪除")
    deleteInfo()
    selectInfo()

    # cursor.execute('drop table student')
    # conn.commit()
main()

繪圖 示例
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

cqlq=pd.read_csv("cqlq.txt",sep="\s+",encoding="gbk")
dxnt=pd.read_csv("dxnt.txt",sep="\s+",encoding="gbk")
ggdq=pd.read_csv("ggdq.txt",sep="\s+",encoding="gbk")
giyy=pd.read_csv("gjyy.txt",sep="\s+",encoding="gbk")



cqlq.columns = ["date","oppr","hipr","lopr","clpr","TR"]
dxnt.columns = ["date","oppr","hipr","lopr","clpr"]
ggdq.columns = ["date","oppr","hipr","lopr","clpr","TR"]
giyy.columns = ["date","oppr","hipr","lopr","clpr","TR"]

a=cqlq
b=dxnt
c=ggdq
d=giyy

ua=(a["clpr"]-a["clpr"].shift(1))/a["clpr"]
ub=(b["clpr"]-b["clpr"].shift(1))/b["clpr"]
uc=(c["clpr"]-c["clpr"].shift(1))/c["clpr"]
ud=(d["clpr"]-d["clpr"].shift(1))/d["clpr"]

u=pd.concat([ua,ub,uc,ud],axis=1)
u.dropna()
miu=u.mean()+0.005
jz=u.cov()
yi = np.ones(4)

miu= np.mat(miu)
jz = np.mat(jz)
yi = np.mat(yi)
nijz = jz.I

a = miu*nijz*miu.T
b =yi*nijz*miu.T
c = yi*nijz*yi.T
deta=a*c-b**2


stock_y=[i*0.0001 for i in range(100)]
stock_x=[(np.sqrt(( c/deta)*(rp-b/c)**2+1/c)).max() for rp in stock_y]

plt.rcParams['font.sans-serif']=['SimHei']
plt.plot(stock_x,stock_y)
plt.xlabel("方差")
plt.ylabel("期望")
print(miu)
print(jz)

plt.show()


使用正則匹配數字
import re
pattern = '\d+?\.\d+'
s = "[Decimal('90.900000')]"
s2 = "[Decimal('75.900000'),Decimal('57.280000')]"
[print(i,end = " ") for i in re.findall(pattern,s)]
print()
[print(i,end = " ") for i in re.findall(pattern,s2)]


0528習題
'''
1.    編寫程式實現:計算並輸出標準輸入的三個數中絕對值最小的數。
'''
#計算並輸出標準輸入的三個數中絕對值最小的數。
import math
num1 = int(input())
num2 = int(input())
num3 = int(input())
num_list = (num1, num2, num3)
index_min = 0    #絕對值最小的元素的下標
if math.fabs(num_list[index_min]) > math.fabs(num_list[1]):
    index_min = 1
if math.fabs(num_list[index_min]) > math.fabs(num_list[2]):
    index_min = 2

for n in num_list:
    if math.fabs(num_list[index_min]) == math.fabs(n):
        print(n, end=' ')

'''
2.    編寫程式,功能是輸入五分製成績,
輸出對應的百分制分數檔。 不考慮非法輸入的情形。
對應關係為:A: 90~100, B: 80~89, C: 70~79,D: 60~69, E: 0~59
'''
score = int(input())
if 90 <= score <= 100:
    print("A")
elif 80 <= score <= 89:
    print("B")
elif 70 <= score <= 79:
    print("C")
elif 60 <= score <= 69:
    print("D")
elif 0 <= score <= 59:
    print("E")
else:
    print("請輸入正確分數")

'''
3.    編寫程式,
輸入年(year)、月(month),輸出該年份該月的天數。
公曆閏年的計算方法為:年份能被4整除且不能被100整除的為閏年;
或者,年份能被400整除的是閏年。
'''
year = int(input("請輸入年份"))
month = int(input("請輸入月份"))
month_lst = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year %4 == 0 and year % 100 !=0) and year % 400 == 0:
    month_lst[1] = 29
print(month_lst[month - 1])

'''
4.    編寫程式,功能是輸入一個數,輸出該數的絕對值
'''
num = int(input())
print(abs(num))

'''
5.    編寫“猜數遊戲”程式,
功能是:
如果使用者輸入的數等於程式選定的數(該數設定為10),則輸出“you win”,
否則如果大於選定的數,則輸出“too big”,反之輸出“too small”。
'''
num = 10
your_num = int(input())
if your_num == num:
    print("you win")
elif your_num > num:
    print("too big")
else:
    print("too small")

關於某一爬蟲例項的總結
os.chdir(r"C:\Users\47311\Desktop\code\") #修改為自己檔案路徑
data = pd.read_excel(r"公司公告2020.xlsx")[:-1] #讀入資料,並刪除最後一行(最後一行為空值)
讀取的資料在 chdir 之下
存在多個數據時,使用字串型別進行 split 分割 "
可能會出錯,需要異常處理 
DataFrame 物件.apply(函式名) 
經常會使用,可以用來賦值新的值

def address(str):            #定義提取公告地址函式
    try:
        return str.split('"')[1]
    except:
        pass
data["公告地址"] = data["公告地址"].apply(address)

對程式碼進行獲取某一個值時 
可以先獲取資料上面的內容
html = requests.get(url).text
使用 etree.HTML(html) 進行解析
使用 xpath 讀取路徑
tree.xpath("xxxx")

返回讀取到的內容,對原內容進行更新
return "http://xxxx.com/" + url[0]

data.iterrows()
讀取每一行的資料
for index, row in data.iterrows():
row['屬性'] 進行獲取值

新增檔案字尾

name = row['公告標題'].split(':')[0] + row["證券程式碼"][:6] + "_" + row["公告日期"] + ".pdf"

爬取時,進行必要的條件資訊的說明

使用 urlretrieve(url,filename = r' xxx ')
進行儲存

當獲取到的資料不存在時,可以通過設定一個 len( data )
設定一個長度 ,過濾掉 不到長度的資料

設定一個布林型別的全域性變數
當訪問到時 設定為 True
如果沒有訪問到,則設定為 False
根據全域性變數的值,判斷是否繼續進行訪問
是否感染病毒
import random
ganran = float(input("請輸入感染概率"))
is_person_ganran = False
# 人是否感染了
person_ganran = random.randint(0,100)
if person_ganran /100 < ganran:
    is_person_ganran = True
print(person_ganran)

if is_person_ganran:
    print("被感染了")
else:
    print("還是正常人")

python檔案操作

file = open('abc.txt','r',encoding='utf-8') 

file = open('abc.txt','w',encoding='utf-8')

'w' 寫入模式
會清空掉檔案,然後再寫入
不想完全覆蓋掉原檔案的話,使用'a' 

關鍵字with,with open(xxx) as f
避免開啟檔案後忘記關閉

readline() 讀取一行

讀取出來的資料 後面都有\n

readlines() 將每一行形成一個元素,放到一個列表中


seek操作

seek(n)游標移動到n位置
注意: 移動單位是byte
如果是utf-8的中文部分要是3的倍數

seek(0,0)預設為0,移動到檔案頭

seek(0,1)移動到當前位置

seek(0,2)移動到檔案尾


tell()  獲取當前游標在什麼位置

修改檔案

將檔案中的內容讀取到記憶體中
將資訊修改完畢, 然後將原始檔刪除, 將新檔案的名字改成原來檔案的名字
可以一行一行的讀取修改,避免溢位

pandas 幾個重要知識點
將 NaN 替換成某一數值
使用 fillna 
dataframe.fillna(value = 'xxx',inplace=True)

刪除某一個值
使用 drop 
dataframe.drop(10,inplace=True)


交換兩行的值

    if m != n:
        temp = np.copy(dataframe[m])
        dataframe[m] = dataframe[n]
        dataframe[n] = temp
    else:
        temp = np.copy(dataframe[dataframe.shape[1]-1])
        dataframe[dataframe.shape[1]-1] = dataframe[n]
        dataframe[n] = temp


刪除 columns 這些列

    dataframe.drop(columns = list, inplace=True)

一千美元的故事(錢放入信封中)
def dollar(n):
    global story_money
    money = []
    for i in range(10):
        if 2**(i+1) > story_money-sum(money):
            money.append(story_money-2**i+1)
            break
        money.append(2 ** i)
    # print(money)
    answer = []
    if n >= money[-1]:
        answer.append(10)
        n -= money[-1]
    n = list(bin(n))[2:]
    n.reverse()
    rank = 1
    for i in n:
        if i == '1':
            answer.append(rank)
        rank += 1
    print(answer)

story_money = 1000
dollar(500)

給定兩個列表,轉換為DataFrame型別
import pandas as pd

def get_data():
    q1 = []
    q2 = []
    p1 = input("list 1:")
    p2 = input("list 2:")
    q1=p1.split(',')
    q2=p2.split(',')
    for i,j in zip(range(len(q1)),range(len(q2))):
        q1[i] = int(q1[i])**1
        q2[j] = float(q2[j])**2
    dic = {
        "L":q1,
        "I":q2
    }
    A = pd.DataFrame(dic)
    print(A)

get_data()


1.將輸入的使用 split(',') 進行分割

2.使用 for i,j in zip(range(len(q1)),range(len(q2)))
對 q1 和 q2 都進行遍歷

3.使用字典,將列表作為值,傳遞過去
使用 pd.DataFrame 進行轉換

通過文件算學生的平均分
tom 85 90
jerry 95 80
lucy 80 90
rose 88 90
jay 76 75
summer 87 85
horry 84 80
dic = {}
with open('score.txt','r') as f:
    lines = f.readlines()
    f.close()
    for line in lines:
        line = line.strip('\n').split(' ')
        dic[line[0]] = (int(line[1]),int(line[2]))
name = input()
if name not in dic.keys():
    print("not found")
else:
    print(sum(dic[name])/len(dic[name]))

0528習題 11-15
'''
6.    一元二次方程:ax2+bx+c=0 (a ╪ 0)
【輸入形式】輸入a、b和c的值(有理數)
【輸出形式】輸出x的兩個值,或者No(即沒有有理數的解)

'''
import math
a = int(input())
b = int(input())
c = int(input())
disc = b*b - 4*a*c
p = -b/(2*a)
if disc > 0:
    q = math.sqrt(disc)/(2*a)
    x1 = p + q
    x2 = p - q
    print("x1 = %s,x2 = %s"%(str(x1,x2)))
elif disc == 0:
    x1 = p
    print("x1 = x2 = ",x1)
else:
    disc = -disc
    q = math.sqrt(disc)/(2*a)
    print("x1 = ",p,"+",q)
    print("x2 = ", p, "-", q)

'''
7.    計算1+1/2+1/3+...+1/n
'''
n = int(input())
sum = 0
for i in range(1,n+1):
    sum += 1/i
print(sum)

'''
8.    編寫猜數遊戲程式,功能是:允許使用者反覆輸入數,
直至猜中程式選定的數(假定為100)。
輸入的數如果大於選定的數,則提示"larger than expected";
如果小於選定的數,則提示"less than expected";
如果等於選定的數,則輸出"you win"並結束程式。
'''
import random
num = random.randint(1,5)
while True:
    your_num = int(input())
    if your_num == num:
        print("you win")
        break
    elif your_num > num:
        print("larger than expected")
    else:
        print("less than expected")

'''
9.    計算1-100之間的偶數和
'''
num_lst = [i for i in range(1,101) if i % 2 == 0]
print(sum(num_lst))

'''
10.    猴子摘下若干個桃子,第一天吃了桃子的一半多一個,
以後每天吃了前一天剩下的一半多一個,
到第n天吃以前發現只剩下一個桃子,
編寫程式實現:據輸入的天數計算並輸出猴子共摘了幾個桃子
【輸入形式】輸入的一行為一個非負整數,表示一共吃的天數。
【輸出形式】輸出的一行為一個非負整數,表示共摘了幾個桃子,
若輸入的資料不合法(如:負數或小數),則輸出"illegal data"。
'''
def Peach(day,yesterday_sum,now_rest):
    if day != 0:
        day -= 1
        yesterday_sum = (now_rest + 1) * 2
        now_rest = yesterday_sum
        return Peach(day,yesterday_sum,now_rest)
    else:
        return yesterday_sum
yesterday_sum = 0
now_rest = 1
day = int(input())
if day <= 0:
    print("illegal data")
    exit()
print(Peach(day,yesterday_sum,now_rest))

0528習題 6-10
'''
1.    編寫程式,功能是把輸入的字串的大寫字母變成小寫字母,
小寫字母變成大寫字母,非字母的字元不作變換。輸出變換後的結果
'''
string = input()
s = ''
for str in string:
    if 'a' <= str <= 'z':
        s += str.upper()
    elif 'A' <= str <= 'Z':
        s += str.lower()
    else:
        s += str
print(s)    

'''
2.    已知10個四位數輸出所有對稱數及個數 n,
例如1221、2332都是對稱數。
【輸入形式】10個四位數,以空格分隔開
【輸出形式】輸入的四位數中的所有對稱數,對稱數個數
'''
input_nums = input().split()
nums = []
for num in input_nums:
    nums.append(int(num))
symmetric_num = []
for num in nums:
    num = str(num)
    if num[0] == num[3] and num[1] == num[2]:
        symmetric_num.append(num)
print("對稱數:")
[print(i,end = " ") for i in symmetric_num]
print(len(symmetric_num))
# 1221 2243 2332 1435 1236 5623 4321 4356 6754 3234

'''
學校舉辦新生歌手大賽,每個選手的成績
由評委的評分去掉一個最高分和一個最低分剩下評分的平均值得到。‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬
編寫程式實現:輸入第一行指定n,從第二行開始每行輸入一個評委的得分(共n行),
計算選手的成績,並輸出。‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬‬
'''
n = int(input())
player = []
for i in range(n):
    score = float(input())
    player.append(score)
player.remove(max(player))
player.remove(min(player))
print("%.1f"%(sum(player)/len(player)))

'''
1.    編寫程式實現:計算並輸出標準輸入的三個數中絕對值最小的數。
'''
#計算並輸出標準輸入的三個數中絕對值最小的數。
import math
num1 = int(input())
num2 = int(input())
num3 = int(input())
num_list = (num1, num2, num3)
index_min = 0    #絕對值最小的元素的下標
if math.fabs(num_list[index_min]) > math.fabs(num_list[1]):
    index_min = 1
if math.fabs(num_list[index_min]) > math.fabs(num_list[2]):
    index_min = 2

for n in num_list:
    if math.fabs(num_list[index_min]) == math.fabs(n):
        print(n, end=' ')

'''
5.    從鍵盤輸入非0整數,以輸入0為輸入結束標誌,求平均值,統計正數負數個數
【輸入形式】 每個整數一行。最後一行是0,表示輸入結束。
【輸出形式】輸出三行。
     第一行是平均值。第二行是正數個數。第三行是負數個數。
'''
nums = []
n_z = 0
n_f = 0
while True:
    num = int(input())
    if num == 0:
        print(sum(nums)/len(nums))
        for n in nums:
            if n > 0:
                n_z += 1
            elif n < 0:
                n_f += 1
        print(n_z)
        print(n_f)
        exit()
    else:
        nums.append(num)

0528習題 16-20
'''
11.    編寫程式,判斷一個數是不是素數,是則輸出“Yes”,不是輸出“No”.(while迴圈)
'''
num = int(input())
i = 2
flag = True
while i < num:
    if num % i ==0:
        flag = False
    i += 1
if flag:
    print("Yes")
else:
    print("No")

'''
12.    程式設計實現:從鍵盤輸入5個分數,計算平均分。
【輸入形式】5個分數,每個分數佔一行。
    【輸出形式】新起一行輸出平均分。
'''
nums = []
for i in range(5):
    num = float(input())
    nums.append(num)
print(sum(nums)/len(nums))

'''
13.    輸入3個整數,輸出其中最大的一個 。
'''
nums = []
for i in range(3):
    num = int(input())
    nums.append(num)
print(max(nums))

'''
14.    輸入n,計算n!(n!=1*2*3*...*n)
'''
n = int(input())
sum = 1
for i in range(1,n+1):
    sum *= i
print(sum)

'''
編寫程式,列印菱形圖案,行數n從鍵盤輸入。
下為n=3時的圖案,其中的點號實際為空格。圖案左對齊輸出。
'''
n = 3
for i in range(1, n + 1):
    print("  " * (n - i) + "* " * (2 * i - 1))
for i in range(n-1,0,-1):
    print("  " * (n - i) + "* " * (2 * i - 1))

0528習題 21-25
'''
16.    編寫程式計算學生的平均分。
【輸入形式】輸入的第一行表示學生人數n;
標準輸入的第2至n+1行表示學生成績。
【輸出形式】輸出的一行表示平均分(保留兩位小數)。
若輸入的資料不合法(學生人數不是大於0的整數,
或學生成績小於0或大於100),輸出“illegal input”。
'''

n = int(input())
nums = []
for i in range(n):
    score = float(input())
    if not 0<= score <= 100:
        print("illegal input")
    nums.append(score)
print("%.2f"%(sum(nums)/len(nums)))

'''
17.    請將一萬以內的完全平方數輸出 .
'''
for x in range(1,101):
    y = x*x
    if y <= 10000:
        print(y)
    else:
        break

'''
18.    從鍵盤輸入非0整數,以輸入0為輸入結束標誌,求平均值,統計正數負數個數
【輸入形式】每個整數一行。最後一行是0,表示輸入結束。
【輸出形式】輸出三行。 第一行是平均值。第二行是正數個數。第三行是負數個數。

'''
nums = []
n_z = 0
n_f = 0
while True:
    num = int(input())
    if num == 0:
        print(sum(nums)/len(nums))
        for n in nums:
            if n > 0:
                n_z += 1
            elif n < 0:
                n_f += 1
        print(n_z)
        print(n_f)
        exit()
    else:
        nums.append(num)

'''
【問題描述】從鍵盤輸入一個大寫字母,要求輸出其對應的小寫字母。
【輸入形式】輸入大寫字母,不考慮不合法輸入。
【輸出形式】輸出對應的小寫字母。
【樣例輸入】A
【樣例輸出】a
'''
s = input()
print(s.lower())

'''
【問題描述】
從鍵盤輸入三個字元,按ASCII碼值從小到大排序輸出,字元之間間隔一個空格。
【輸入形式】
輸入三個字元,每個字元用空格隔開。
【輸出形式】
相對應的輸出按照ASCII碼值從小到大排列的三個字元,每個字元間用空格隔開。
【樣例輸入】a c b
【樣例輸出】a b c
'''
strings = input().split(' ')
strings = sorted(strings)
for s in strings:
    print(s,end = " ")


0528習題 26-31
'''
【問題描述】定義一個函式判斷是否為素數isPrime(),
主程式通過呼叫函式輸出2-30之間所有的素數。
素數:一個大於1的自然數,除了1和它本身外,不能被其他自然數整除。
【輸入形式】無【輸出形式】2~30之間所有的索數(逗號分隔)
【樣例輸入】【樣例輸出】2,3,5,7,11,13,17,19,23,29,
【樣例說明】【評分標準】
'''
def isPrime(n):
    i = 2
    flag = True
    while i < n:
        if n % i == 0:
            flag = False
        i += 1
    if flag:
        return True
    else:
        return False
for i in range(2,31):
    if isPrime(i):
        print(i,end = ',')

'''
【問題描述】有182只兔子,分別裝在甲乙兩種籠子裡,
甲種籠子(x)每個裝6只,乙種籠子(y)每個裝4只,
兩種籠子正好用36個,問兩種籠子各用多少個?
【輸入形式】無
【輸出形式】籠子的個數
【樣例輸入】
【樣例輸出】x=*;y=*
【輸出說明】
    1)*代表輸出的值;
    2)輸出的等號和分號都是英文字元
'''
for i in range(1,36):
    x = i
    y = 36 - i
    if 6*x + 4*y == 182:
        print("x=%d;y=%d"%(x,y))

'''
輸入圓柱體的底面半徑和高,求圓柱體的體積並輸出。
圓周率T取固定值3.14。
【輸入形式】圓柱體的底面半徑和高
【輸出形式】圓柱體的體積
【樣例輸入】2
【樣例輸出】50.24
'''
r = float(input())
h = float(input())
pi = 3.14
print("%.2f"%(pi*r*r*h))

'''
【問題描述】猴子吃桃問題:
猴子摘下若干個桃子,第一天吃了桃子的一半多一個,
以後每天吃了前一天剩下的一半多一個,
到第n天吃以前發現只剩下一個桃子,
編寫程式實現:據輸入的天數計算並輸出猴子共摘了幾個桃子。
【輸入形式】n。
【輸出形式】共摘了幾個桃子
【樣例輸入】3
【樣例輸出】10
【樣例輸入】1
【樣例輸出】1
'''
day = int(input())
now = 1
yesterday = 0
while day > 1:
    yesterday = (now + 1) * 2
    now = yesterday
    day -= 1
print(now)

'''
輸入5名學生的成績,儲存到列表,
統計最高分、最低分、平均分和及格率。平均分
和及格率保留兩位小數,及格率的輸出格式為x%。
【輸入形式】5個人的成績
【輸出形式】最高分、最低分、平均分、及格率
【樣例輸入】
56
67
55
66
70
【樣例輸出】
70
55
62.80
60.00%
'''
score = []
for i in range(5):
    num = float(input())
    score.append(num)
n = 0
for i in score:
    if i > 60:
        n += 1

print(max(score))
print(min(score))
print(sum(score)/len(score))
print("%.2f%%"%(n*100/len(score)))

'''
【問題描述】
檔案“in.txt”中儲存了學生的姓名和成績,
每個人的姓名成績放在一行,中間用空格隔開,
形式如下:Sunny 70 Susan 88從檔案讀取資料後,
存入字典,姓名作為字典的鍵,成績作為字典的值。
然後輸入姓名,查詢相應的成績,查不到,顯示"not found"。
【輸入形式】姓名
【輸出形式】成績
【樣例輸入】鍵盤輸入:Susan
'''
name = input()
flag = False
with open('in.txt','r',encoding='utf-8') as fp:
    for line in fp:
        line = line.replace('\n','')
        if line != "":
            lst = line.split()
            tup = tuple(lst)
            # print(tup)
            if tup[0] == name:
                flag = True
                print(tup[-1])

if not flag:
    print("not found")




in.txt檔案內容
Sunny 70
Susan 80

讀取 csv , xlsx 表格並新增總分列
import pandas as pd
import numpy as np
data = pd.read_excel('學生成績表.csv',columns = ['學號','姓名','高數','英語','計算機'])

sum_score = [ ]
for i in range(len(data)):
    sum_score.append(sum(data.loc[i,:][data.columns[2:]]))
data['總分'] = sum_score
print(data['總分'])
data.to_csv('學生成績表1.csv',encoding='gbk')

matplotlib 顯示中文問題

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號

十進位制轉換
# bin2dec
# 二進位制 to 十進e5a48de588b662616964757a686964616f31333335336437制: int(str,n=10) 
def bin2dec(string_num):
    return str(int(string_num, 2))
 
# hex2dec
# 十六進位制 to 十進位制
def hex2dec(string_num):
    return str(int(string_num.upper(), 16))
 
# dec2bin
# 十進位制 to 二進位制: bin() 
def dec2bin(string_num):
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num,rem = divmod(num, 2)
        mid.append(base[rem])
 
    return ''.join([str(x) for x in mid[::-1]])
 
# dec2hex
# 十進位制 to 八進位制: oct() 
# 十進位制 to 十六進位制: hex() 
def dec2hex(string_num):
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num,rem = divmod(num, 16)
        mid.append(base[rem])
 
    return ''.join([str(x) for x in mid[::-1]])

base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'), ord('A') + 6)]

def dec2bin(string_num):
    '''十進位制轉換為 二進位制'''
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num, rem = divmod(num, 2)
        mid.append(base[rem])

    return ''.join([str(x) for x in mid[::-1]])

def dec2oct(string_num):
    '''轉換為 八進位制'''
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num, rem = divmod(num, 8)
        mid.append(base[rem])

    return ''.join([str(x) for x in mid[::-1]])


def dec2hex(string_num):
    '''轉換為 十六進位制'''
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num, rem = divmod(num, 16)
        mid.append(base[rem])

    return ''.join([str(x) for x in mid[::-1]])



num = float(input())

print(dec2bin(num),dec2oct(num),dec2hex(num))

正則表示式鞏固
# 匯入re模組
import re

# 使用match方法進行匹配操作
result = re.match(正則表示式,要匹配的字串)

# 如果上一步匹配到資料的話,可以使用group方法來提取資料
result.group()
re.match用來進行正則匹配檢查
若字串匹配正則表示式,則match方法返回匹配物件(Match Object)
否則返回None
import re

result = re.match("itcast","itcast.cn")

result.group()
re.match() 能夠匹配出以xxx開頭的字串


大寫字母表示 非  
\w 匹配字母,數字,下劃線
\W 表示除了字母 數字 下劃線的
import re

ret = re.match(".","a")
ret.group()

ret = re.match(".","b")
ret.group()

ret = re.match(".","M")
ret.group()


import re

# 如果hello的首字元小寫,那麼正則表示式需要小寫的h
ret = re.match("h","hello Python")
ret.group()


# 如果hello的首字元大寫,那麼正則表示式需要大寫的H
ret = re.match("H","Hello Python")
ret.group()

# 大小寫h都可以的情況
ret = re.match("[hH]","hello Python")
ret.group()
ret = re.match("[hH]","Hello Python")
ret.group()

# 匹配0到9第一種寫法
ret = re.match("[0123456789]","7Hello Python")
ret.group()

# 匹配0到9第二種寫法
ret = re.match("[0-9]","7Hello Python")
ret.group()

import re

# 普通的匹配方式
ret = re.match("嫦娥1號","嫦娥1號發射成功")
print(ret.group())

ret = re.match("嫦娥2號","嫦娥2號發射成功")
print(ret.group())

ret = re.match("嫦娥3號","嫦娥3號發射成功")
print(ret.group())

# 使用\d進行匹配
ret = re.match("嫦娥\d號","嫦娥1號發射成功")
print(ret.group())

ret = re.match("嫦娥\d號","嫦娥2號發射成功")
print(ret.group())

ret = re.match("嫦娥\d號","嫦娥3號發射成功")
print(ret.group())


正則表示式裡使用"\"作為轉義字元
需要匹配文字中的字元"\"
使用反斜槓"\\"


import re

ret = re.match("[A-Z][a-z]*","Mm")
print(ret.group())

ret = re.match("[A-Z][a-z]*","Aabcdef")
print(ret.group())


import re

ret = re.match("[a-zA-Z_]+[\w_]*","name1")
print(ret.group())

ret = re.match("[a-zA-Z_]+[\w_]*","_name")
print(ret.group())

ret = re.match("[a-zA-Z_]+[\w_]*","2_name")
print(ret.group())

import re

ret = re.match("[1-9]?[0-9]","7")
print(ret.group())

ret = re.match("[1-9]?[0-9]","33")
print(ret.group())

ret = re.match("[1-9]?[0-9]","09")
print(ret.group())

import re

ret = re.match("[a-zA-Z0-9_]{6}","12a3g45678")
print(ret.group())

ret = re.match("[a-zA-Z0-9_]{8,20}","1ad12f23s34455ff66")
print(ret.group())


import re

# 正確的地址
ret = re.match("[\w]{4,20}@163\.com", "[email protected]")
print(ret.group())

# 不正確的地址
ret = re.match("[\w]{4,20}@163\.com", "[email protected]")
print(ret.group())

# 通過$來確定末尾
ret = re.match("[\w]{4,20}@163\.com$", "[email protected]")
print(ret.group())

\b    匹配一個單詞的邊界
\B    匹配非單詞邊界


import re

ret = re.match("[1-9]?\d","8")
print(ret.group())

ret = re.match("[1-9]?\d","78")
print(ret.group())


# 新增|
ret = re.match("[1-9]?\d$|100","8")
print(ret.group())

ret = re.match("[1-9]?\d$|100","78")
print(ret.group())

ret = re.match("[1-9]?\d$|100","100")
print(ret.group())


import re

ret = re.match("\w{4,20}@163\.com", "[email protected]")
print(ret.group())

ret = re.match("\w{4,20}@(163|126|qq)\.com", "[email protected]")
print(ret.group())

ret = re.match("\w{4,20}@(163|126|qq)\.com", "[email protected]")
print(ret.group())


import re

# 能夠完成對正確的字串的匹配
ret = re.match("<[a-zA-Z]*>\w*</[a-zA-Z]*>", "<html>hh</html>")
print(ret.group())

# 如果遇到非正常的html格式字串,匹配出錯
ret = re.match("<[a-zA-Z]*>\w*</[a-zA-Z]*>", "<html>hh</htmlbalabala>")
print(ret.group())

# 正確的理解思路:如果在第一對<>中是什麼,按理說在後面的那對<>中就應該是什麼

# 通過引用分組中匹配到的資料即可,但是要注意是元字串,即類似 r""這種格式
ret = re.match(r"<([a-zA-Z]*)>\w*</\1>", "<html>hh</html>")
print(ret.group())

# 因為2對<>中的資料不一致,所以沒有匹配出來
ret = re.match(r"<([a-zA-Z]*)>\w*</\1>", "<html>hh</htmlbalabala>")
print(ret.group())

import re

ret = re.match(r"<(\w*)><(\w*)>.*</\2></\1>", "<html><h1>www.itcast.cn</h1></html>")
print(ret.group())

# 因為子標籤不同,導致出錯
ret = re.match(r"<(\w*)><(\w*)>.*</\2></\1>", "<html><h1>www.itcast.cn</h2></html>")
print(ret.group())

import re

ret = re.match(r"<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h1></html>")
print(ret.group())

ret = re.match(r"<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h2></html>")
print(ret.group())


import re
ret = re.search(r"\d+", "閱讀次數為 9999")
print(ret.group())

import re
ret = re.findall(r"\d+", "python = 9999, c = 7890, c++ = 12345")
print(ret)

import re
ret = re.sub(r"\d+", '998', "python = 997")
print(ret)

import re

def add(temp):
    strNum = temp.group()
    num = int(strNum) + 1
    return str(num)

# 替換的是 原資料 + 1
ret = re.sub(r"\d+", add, "python = 997")
print(ret)

ret = re.sub(r"\d+", add, "python = 99")
print(ret)

import re
ret = re.split(r":| ","info:xiaoZhang 33 shandong")
print(ret)

Python裡數量詞預設是貪婪的  匹配儘可能多的字元

非貪婪 總匹配儘可能少的字元。


pandas鞏固
導包
import pandas as pd
設定輸出結果列對齊
pd.set_option('display.unicode.ambiguous_as_wide',True)
pd.set_option('display.unicode.east_asian_width',True)
建立 從 0 開始的非負整數索引
s1 = pd.Series(range(1,20,5))
使用字典建立 Series 字典的鍵作為索引
s2 = pd.Series({'語文':95,'數學':98,'Python':100,'物理':97,'化學':99})
修改 Series 物件的值
s1[3] = -17
檢視 s1 的絕對值
abs(s1)
將 s1 所有的值都加 5、使用加法時,對所有元素都進行
s1 + 5
在 s1 的索引下標前加入引數值
s1.add_prefix(2)
s2 資料的直方圖
s2.hist()
每行索引後面加上 hany
s2.add_suffix('hany')
檢視 s2 中最大值的索引
s2.argmax()
檢視 s2 的值是否在指定區間內
s2.between(90,100,inclusive = True)
檢視 s2 中 97 分以上的資料
s2[s2 > 97]
檢視 s2 中大於中值的資料
s2[s2 > s2.median()]
s2 與數字之間的運算,開平方根 * 10 保留一位小數
round((s2**0.5)*10,1)
s2 的中值
s2.median()
s2 中最小的兩個數
s2.nsmallest(2)
s2 中最大的兩個數
s2.nlargest(2)
Series 物件之間的運算,對相同索引進行計算,不是相同索引的使用 NaN
pd.Series(range(5)) + pd.Series(range(5,10))
對 Series 物件使用匿名函式
pd.Series(range(5)).pipe(lambda x,y,z :(x**y)%z,2,5)
pd.Series(range(5)).pipe(lambda x:x+3)
pd.Series(range(5)).pipe(lambda x:x+3).pipe(lambda x:x*3)
對 Series 物件使用匿名函式
pd.Series(range(5)).apply(lambda x:x+3)
檢視標準差
pd.Series(range(0,5)).std()
檢視無偏方差
pd.Series(range(0,5)).var()
檢視無偏標準差
pd.Series(range(0,5)).sem()
檢視是否存在等價於 True 的值
any(pd.Series([3,0,True]))
檢視是否所有的值都等價於 True
all(pd.Series([3,0,True]))

建立一個 DataFrame 物件
dataframe = pd.DataFrame(np.random.randint(1,20,(5,3)),
                         index = range(5),
                         columns = ['A','B','C'])
索引為時間序列
dataframe2 = pd.DataFrame(np.random.randint(5,15,(9,3)),
                          index = pd.date_range(start = '202003211126',
                                                end = '202003212000',
                                                freq = 'H'),
                          columns = ['Pandas','爬蟲','比賽'])
使用字典進行建立
dataframe3 = pd.DataFrame({'語文':[87,79,67,92],
                           '數學':[93,89,80,77],
                           '英語':[88,95,76,77]},
                          index = ['張三','李四','王五','趙六'])
建立時自動擴充
dataframe4 = pd.DataFrame({'A':range(5,10),'B':3})
檢視周幾
dff['日期'] = pd.to_datetime(data['日期']).dt.weekday_name
按照周幾進行分組,檢視交易的平均值
dff = dff.groupby('日期').mean().apply(round)
dff.index.name = '周幾'
對姓名和日期進行分組,並進行求和
dff = dataframe.groupby(by = ['姓名','日期'],as_index = False).sum()
將 dff 的索引,列 設定成透視表形式
dff = dff.pivot(index = '姓名',columns = '日期',values = '交易額')
檢視前一天的資料
dff.iloc[:,:1]
交易總額小於 4000 的人的前三天業績
dff[dff.sum(axis = 1) < 4000].iloc[:,:3]
工資總額大於 2900 元的員工的姓名
dff[dff.sum(axis = 1) > 2900].index.values
顯示前兩天每一天的交易總額以及每個人的交易金額
dataframe.pivot_table(values = '交易額',index = '姓名',
                      columns = '日期',aggfunc = 'sum',margins = True).iloc[:,:2]
顯示每個人在每個櫃檯的交易總額
dff = dataframe.groupby(by = ['姓名','櫃檯'],as_index = False).sum()
dff.pivot(index = '姓名',columns = '櫃檯',values = '交易額')
檢視每人每天的上班次數
dataframe.pivot_table(values = '交易額',index = '姓名',columns = '日期',aggfunc = 'count',margins = True).iloc[:,:1]
檢視每個人每天購買的次數
dataframe.pivot_table(values = '交易額',index = '姓名',columns = '日期',aggfunc = 'count',margins = True)
每個人每天上過幾次班
pd.crosstab(dataframe.姓名,dataframe.日期,margins = True).iloc[:,:2]
每個人每天去過幾次櫃檯
pd.crosstab(dataframe.姓名,dataframe.櫃檯)
將每一個人在每一個櫃檯的交易總額顯示出來
pd.crosstab(dataframe.姓名,dataframe.櫃檯,dataframe.交易額,aggfunc='sum')
每個人在每個櫃檯交易額的平均值,金額/天數
pd.crosstab(dataframe.姓名,dataframe.櫃檯,dataframe.交易額,aggfunc = 'mean').apply(lambda  num:round(num,2) )
對 5 的餘數進行分組
dataframe.groupby(by = lambda num:num % 5)['交易額'].sum()
檢視索引為 7 15 的交易額
dataframe.groupby(by = {7:'索引為7的行',15:'索引為15的行'})['交易額'].sum()
檢視不同時段的交易總額
dataframe.groupby(by = '時段')['交易額'].sum()
各櫃檯的銷售總額
dataframe.groupby(by = '櫃檯')['交易額'].sum()
檢視每個人在每個時段購買的次數
count = dataframe.groupby(by = '姓名')['時段'].count()
每個人的交易額平均值並排序
dataframe.groupby(by = '姓名')['交易額'].mean().round(2).sort_values()
每個人的交易額,apply(int) 轉換為整數
dataframe.groupby(by = '姓名').sum()['交易額'].apply(int)
每一個員工交易額的中值
data = dataframe.groupby(by = '姓名').median()
檢視交易額對應的排名
data['排名'] = data['交易額'].rank(ascending = False)
data[['交易額','排名']]
每個人不同時段的交易額
dataframe.groupby(by = ['姓名','時段'])['交易額'].sum()
設定各時段累計
dataframe.groupby(by = ['姓名'])['時段','交易額'].aggregate({'交易額':np.sum,'時段':lambda x:'各時段累計'})
對指定列進行聚合,檢視最大,最小,和,平均值,中值
dataframe.groupby(by = '姓名').agg(['max','min','sum','mean','median'])
檢視部分聚合後的結果
dataframe.groupby(by = '姓名').agg(['max','min','sum','mean','median'])['交易額']
檢視交易額低於 2000 的三條資料
dataframe[dataframe.交易額 < 2000][:3]
檢視上浮了 50% 之後依舊低於 1500 的交易額,檢視 4 條資料
dataframe.loc[dataframe.交易額 < 1500,'交易額'] = dataframe[dataframe.交易額 < 1500]['交易額'].map(lambda num:num*1.5)
檢視交易額大於 2500 的資料
dataframe[dataframe.交易額 > 2500]
檢視交易額低於 900 或 高於 1800 的資料
dataframe[(dataframe.交易額 < 900)|(dataframe.交易額 > 1800)]
將所有低於 200 的交易額都替換成 200
dataframe.loc[dataframe.交易額 < 200,'交易額'] = 200
檢視低於 1500 的交易額個數
dataframe.loc[dataframe.交易額 < 1500,'交易額'].count()
將大於 3000 元的都替換為 3000 元
dataframe.loc[dataframe.交易額 > 3000,'交易額'] = 3000
檢視有多少行資料
len(dataframe)
丟棄缺失值之後的行數
len(dataframe.dropna())
包含缺失值的行
dataframe[dataframe['交易額'].isnull()]
使用固定值替換缺失值
dff = copy.deepcopy(dataframe)
dff.loc[dff.交易額.isnull(),'交易額'] = 999
使用交易額的均值替換缺失值
dff = copy.deepcopy(dataframe)
for i in dff[dff.交易額.isnull()].index:
    dff.loc[i,'交易額'] = round(dff.loc[dff.姓名 == dff.loc[i,'姓名'],'交易額'].mean())
使用整體均值的 80% 填充缺失值
dataframe.fillna({'交易額':round(dataframe['交易額'].mean() * 0.8)},inplace = True)
檢視重複值
dataframe[dataframe.duplicated()]
丟棄重複行
dataframe = dataframe.drop_duplicates()
檢視員工業績波動情況(每一天和昨天的資料作比較)
dff = dataframe.groupby(by = '日期').sum()['交易額'].diff()
對資料使用 map 函式
dff.map(lambda num:'%.2f'%(num))[:5]
檢視張三的波動情況
dataframe[dataframe.姓名 == '張三'].groupby(by = '日期').sum()['交易額'].diff()
修改異常值
data.loc[data.交易額 > 3000,'交易額'] = 3000
data.loc[data.交易額 < 200,'交易額'] = 200
刪除重複值
data.drop_duplicates(inplace = True)
填充缺失值
data['交易額'].fillna(data['交易額'].mean(),inplace = True)
使用交叉表得到每人在各櫃檯交易額的平均值
data_group = pd.crosstab(data.姓名,data.櫃檯,data.交易額,aggfunc = 'mean').apply(round)
繪製柱狀圖
data_group.plot(kind = 'bar')
使用 concat 連線兩個相同結構的 DataFrame 物件
df3 = pd.concat([df1,df2])
合併,忽略原來的索引 ignore_index
df4 = df3.append([df1,df2],ignore_index = True)
按照列進行拆分
df5 = df4.loc[:,['姓名','櫃檯','交易額']]
按照工號進行合併,隨機檢視 3 條資料
rows = np.random.randint(0,len(df5),3)
pd.merge(df4,df5).iloc[rows,:]
按照工號進行合併,指定其他同名列的字尾
pd.merge(df1,df2,on = '工號',suffixes = ['_x','_y']).iloc[:,:]
兩個表都設定工號為索引 set_index
df2.set_index('工號').join(df3.set_index('工號'),lsuffix = '_x',rsuffix = '_y').iloc[:]
按照交易額和工號降序排序,檢視五條資料
dataframe.sort_values(by = ['交易額','工號'],ascending = False)[:5]
按照交易額和工號升序排序,檢視五條資料
dataframe.sort_values(by = ['交易額','工號'])[:5]
按照交易額降序和工號升序排序,檢視五條資料
dataframe.sort_values(by = ['交易額','工號'],ascending = [False,True])[:5]
按工號升序排序
dataframe.sort_values(by = ['工號'])[:5]
按列名升序排序
dataframe.sort_index(axis = 1)[:5]
每隔五天--5D
pd.date_range(start = '20200101',end = '20200131',freq = '5D')
每隔一週--W
pd.date_range(start = '20200301',end = '20200331',freq = 'W')
間隔兩天,五個資料
pd.date_range(start = '20200301',periods = 5,freq = '2D')
間隔三小時,八個資料
pd.date_range(start = '20200301',periods = 8,freq = '3H')
三點開始,十二個資料,間隔一分鐘
pd.date_range(start = '202003010300',periods = 12,freq = 'T')
每個月的最後一天
pd.date_range(start = '20190101',end = '20191231',freq = 'M')
間隔一年,六個資料,年末最後一天
pd.date_range(start = '20190101',periods = 6,freq = 'A')
間隔一年,六個資料,年初最後一天
pd.date_range(start = '20200101',periods = 6,freq = 'AS')
使用 Series 物件包含時間序列物件,使用特定索引
data = pd.Series(index = pd.date_range(start = '20200321',periods = 24,freq = 'H'),data = range(24))
三分鐘重取樣,計算均值
data.resample('3H').mean()
五分鐘重取樣,求和
data.resample('5H').sum()
計算OHLC open,high,low,close
data.resample('5H').ohlc()
將日期替換為第二天
data.index = data.index + pd.Timedelta('1D')
檢視指定日期的年份是否是閏年
pd.Timestamp('20200301').is_leap_year
檢視指定日期所在的季度和月份
day = pd.Timestamp('20200321')
檢視日期的季度
day.quarter
檢視日期所在的月份
day.month
轉換為 python 的日期時間物件
day.to_pydatetime()

檢視所有的交易額資訊
dataframe['交易額'].describe()
檢視四分位數
dataframe['交易額'].quantile([0,0.25,0.5,0.75,1.0])
檢視最大的交易額資料
dataframe.nlargest(2,'交易額')
檢視最後一個日期
dataframe['日期'].max()
檢視最小的工號
dataframe['工號'].min()
第一個最小交易額的行下標
index = dataframe['交易額'].idxmin()
第一個最小交易額
dataframe.loc[index,'交易額']
最大交易額的行下標
index = dataframe['交易額'].idxmax()
跳過 1 2 4 行,以第一列姓名為索引
dataframe2 = pd.read_excel('超市營業額.xlsx',
                           skiprows = [1,2,4],
                           index_col = 1)
檢視 5 到 10 的資料
dataframe[5:11]
檢視第六行的資料
dataframe.iloc[5]
檢視第 1 3 4 行的資料
dataframe.iloc[[0,2,3],:]
檢視第 1 3 4 行的第 1 2 列
dataframe.iloc[[0,2,3],[0,1]]
檢視前五行指定,姓名、時段和交易額的資料
dataframe[['姓名','時段','交易額']][:5]
檢視第 2 4 5 行 姓名,交易額 資料 loc 函式
dataframe.loc[[1,3,4],['姓名','交易額']]
檢視第四行的姓名資料
dataframe.at[3,'姓名']
某一時段的交易總和
dataframe[dataframe['時段'] == '14:00-21:00']['交易額'].sum()
檢視張三總共的交易額
dataframe[dataframe['姓名'].isin(['張三'])]['交易額'].sum()
檢視日用品的銷售總額
dataframe[dataframe['櫃檯'] == '日用品']['交易額'].sum()
檢視交易額在 1500~3000 之間的記錄
dataframe[dataframe['交易額'].between(1500,3000)]
將日期設定為 python 中的日期型別
data.日期 = pd.to_datetime(data.日期)
每七天營業的總額
data.resample('7D',on = '日期').sum()['交易額']
每七天營業總額
data.resample('7D',on = '日期',label = 'right').sum()['交易額']
每七天營業額的平均值
func = lambda item:round(np.sum(item)/len(item),2)
data.resample('7D',on = '日期',label = 'right').apply(func)['交易額']
每七天營業額的平均值
func = lambda num:round(num,2)
data.resample('7D',on = '日期',label = 'right').mean().apply(func)['交易額']
刪除工號這一列
data.drop('工號',axis = 1,inplace = True)
按照姓名和櫃檯進行分組彙總
data = data.groupby(by = ['姓名','櫃檯']).sum()
檢視張三的彙總資料
data.loc['張三',:]
檢視張三在蔬菜水果的交易資料
data.loc['張三','蔬菜水果']
丟棄工號列
data.drop('工號',axis = 1,inplace = True)
按照櫃檯進行排序
dff = data.sort_index(level = '櫃檯',axis = 0)
按照姓名進行排序
dff = data.sort_index(level = '姓名',axis = 0)
按照櫃檯進行分組求和
dff = data.groupby(level = '櫃檯').sum()['交易額']
平均值
data.mean()
標準差
data.std()
協方差
data.cov()
刪除缺失值和重複值,inplace = True 直接丟棄
data.dropna(inplace = True)
data.drop_duplicates(inplace = True)

numpy鞏固
導包
import numpy as np
建立二維陣列
x = np.matrix([[1,2,3],[4,5,6]])
建立一維陣列
y = np.matrix([1,2,3,4,5,6])
x 的第二行第二列元素
x[1,1]
矩陣的乘法
x*y
# 相關係數矩陣,可使用在列表元素陣列矩陣
# 負相關
np.corrcoef([1,2,3],[8,5,4])
'''
array([[ 1.        , -0.96076892],
       [-0.96076892,  1.        ]])
'''
# 正相關
np.corrcoef([1,2,3],[4,5,7])
'''
array([[1.        , 0.98198051],
       [0.98198051, 1.        ]])
'''
矩陣的方差
np.cov([1,1,1,1,1])
矩陣的標準差
np.std([1,1,1,1,1])
垂直堆疊矩陣
z = np.vstack((x,y))
矩陣的協方差
np.cov(z)
np.cov(x,y)
標準差
np.std(z)
列向標準差
np.std(z,axis = 1)
方差
np.cov(x)
特徵值和特徵向量
A = np.array([[1,-3,3],[3,-5,3],[6,-6,4]])
e,v = np.linalg.eig(A)
e 為特徵值, v 為特徵向量
矩陣與特徵向量的乘積
np.dot(A,v)
特徵值與特徵向量的乘積
e * v
驗證兩個乘積是否相等
np.isclose(np.dot(A,v),(e * v))
行列式 |A - λE| 的值應為 0
np.linalg.det(A-np.eye(3,3)*e)
逆矩陣
y = np.linalg.inv(x)
矩陣的乘法(注意先後順序)
x * y
'''
matrix([[ 1.00000000e+00,  5.55111512e-17,  1.38777878e-17],
        [ 5.55111512e-17,  1.00000000e+00,  2.77555756e-17],
        [ 1.77635684e-15, -8.88178420e-16,  1.00000000e+00]])
'''
y * x
'''
matrix([[ 1.00000000e+00, -1.11022302e-16,  0.00000000e+00],
        [ 8.32667268e-17,  1.00000000e+00,  2.22044605e-16],
        [ 6.93889390e-17,  0.00000000e+00,  1.00000000e+00]])
'''
求解線性方程組
a = np.array([[3,1],[1,2]])
b = np.array([9,8])
x = np.linalg.solve(a,b)


最小二乘解:返回解,餘項,a 的秩,a 的奇異值
np.linalg.lstsq(a,b)
# (array([2., 3.]), array([], dtype=float64), 2, array([3.61803399, 1.38196601]))
計算向量和矩陣的範數
x = np.matrix([[1,2],[3,-4]])

np.linalg.norm(x)
# 5.477225575051661

np.linalg.norm(x,-2)
# 1.9543950758485487

np.linalg.norm(x,-1)
# 4.0

np.linalg.norm(x,1)
# 6.0

np.linalg.norm([1,2,0,3,4,0],0)
# 4.0

np.linalg.norm([1,2,0,3,4,0],2)
# 5.477225575051661
奇異值分解
a = np.matrix([[1,2,3],[4,5,6],[7,8,9]])

u,s,v = np.linalg.svd(a)

u
'''
matrix([[-0.21483724,  0.88723069,  0.40824829],
        [-0.52058739,  0.24964395, -0.81649658],
        [-0.82633754, -0.38794278,  0.40824829]])
'''
s
'''
array([1.68481034e+01, 1.06836951e+00, 4.41842475e-16])
'''
v
'''
matrix([[-0.47967118, -0.57236779, -0.66506441],
        [-0.77669099, -0.07568647,  0.62531805],
        [-0.40824829,  0.81649658, -0.40824829]])
'''

# 驗證
u * np.diag(s) * v
'''
matrix([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]])
'''

實現矩陣的轉置
x.T
元素平均值
x.mean()
縱向平均值
x.mean(axis = 0)
橫向平均值
x.mean(axis = 1)
所有元素之和
x.sum()
橫向最大值
x.max(axis = 1)
橫向最大值的索引下標
x.argmax(axis = 1)
對角線元素
x.diagonal()
非零元素下標
x.nonzero()
建立陣列

np.array([1,2,3,4])
np.array((1,2,3,4))
np.array(range(4)) # 不包含終止數字
# array([0, 1, 2, 3])
# 使用 arange(初始位置=0,末尾,步長=1)
np.arange(1,8,2)
# array([1, 3, 5, 7])
生成等差陣列,endpoint 為 True 則包含末尾數字
np.linspace(1,3,4,endpoint=False)
# array([1. , 1.5, 2. , 2.5])
np.linspace(1,3,4,endpoint=True)
# array([1.        , 1.66666667, 2.33333333, 3.        ])
建立全為零的一維陣列
np.zeros(3)
建立全為一的一維陣列
np.ones(4)
np.linspace(1,3,4)
# array([1.        , 1.66666667, 2.33333333, 3.        ])
np.logspace(起始數字,終止數字,數字個數,base = 10) 對數陣列
np.logspace(1,3,4)
# 相當於 10 的 linspace(1,3,4) 次方
# array([  10.        ,   46.41588834,  215.443469  , 1000.        ])



np.logspace(1,3,4,base = 2)
# 2 的 linspace(1,3,4) 次方
# array([2.       , 3.1748021, 5.0396842, 8.       ])
建立二維陣列(列表巢狀列表)
np.array([[1,2,3],[4,5,6]])
# 建立全為零的二維陣列
# 兩行兩列
np.zeros((2,2))
三行兩列
np.zeros((3,2))
# 建立一個單位陣列
np.identity(3)

'''
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
'''
建立一個對角矩陣,(引數為對角線上的數字)
np.diag((1,2,3))

'''
array([[1, 0, 0],
       [0, 2, 0],
       [0, 0, 3]])
'''
第一行元素
n[0]
第一行第三列元素
n[0,2]
第一行和第二行的元素
n[[0,1]]
第一行第三列,第三行第二列,第二行第一列
n[[0,2,1],[2,1,0]]
將陣列倒序
a[::-1]
步長為 2
a[::2]
從 0 到 4 的元素
a[:5]
變換 c 的矩陣行和列

c = np.arange(16)
# array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])

c.shape = 4,4
'''
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
'''
第一行,第三個元素到第五個元素(如果沒有則輸出到末尾截止)
c[0,2:5]
第二行元素
c[1]
第三行到第六行,第三列到第六列
c[2:5,2:5]
第二行第三列元素和第三行第四列元素
c[[1,2],[2,3]]
第一行和第三行的第二列到第三列的元素
c[[0,2],1:3]
第一列和第三列的所有橫行元素
c[:,[0,2]]
第三列所有元素
c[:,2]
第二行和第四行的所有元素
c[[1,3]]
第一行的第二列,第四列元素,第四行的第二列,第四列元素
c[[0,3]][:,[1,3]]
使用 * 進行相乘
x*2
使用 / 進行相除
x / 2
2 / x
使用 // 進行整除
x//2
10//x
使用 ** 進行冪運算
x**3
2 ** x
使用 + 進行相加
x + 2
使用 % 進行取模
x % 3
使用 + 進行相加
np.array([1,2,3,4]) + np.array([11,22,33,44])


np.array([1,2,3,4]) + np.array([3])
# array([4, 5, 6, 7])
陣列的內積運算(對應位置上元素相乘)
np.dot(x,y)
sum(x*y)
將陣列中大於 0.5 的元素顯示
n[n>0.5]
找到陣列中 0.05 ~ 0.4 的元素總數
sum((n > 0.05)&(n < 0.4))
是否都大於 0.2
np.all(n > 0.2)
是否有元素小於 0.1
np.any(n < 0.1)
在 a 中是否有大於 b 的元素
a > b
# array([False,  True, False])

# 在 a 中是否有等於 b 的元素
a == b
# array([False, False,  True])

# 顯示 a 中 a 的元素等於 b 的元素
a[a == b]
# array([7])
顯示 a 中的偶數且小於 5 的元素
a[(a%2 == 0) & (a < 5)]
生成一個隨機陣列
np.random.randint(0,6,3)
生成一個隨機陣列(二維陣列)
np.random.randint(0,6,(3,3))
生成十個隨機數在[0,1)之間
np.random.rand(10)
'''
array([0.9283789 , 0.43515554, 0.27117021, 0.94829333, 0.31733981,
       0.42314939, 0.81838647, 0.39091899, 0.33571004, 0.90240897])
'''
從標準正態分佈中隨機抽選出3個數
np.random.standard_normal(3)
返回三頁四行兩列的標準正態分佈數
np.random.standard_normal((3,4,2))
x = np.arange(8)
在陣列尾部追加一個元素
np.append(x,10)
在陣列尾部追加多個元素
np.append(x,[15,16,17])
使用 陣列下標修改元素的值
x[0] = 99
在指定位置插入資料
np.insert(x,0,54)
建立一個多維陣列
x = np.array([[1,2,3],[11,22,33],[111,222,333]])

修改第 0 行第 2 列的元素值
x[0,2] = 9
行數大於等於 1 的,列數大於等於 1 的置為 1
x[1:,1:] = 1
# 同時修改多個元素值
x[1:,1:] = [7,8]
'''
array([[  1,   2,   9],
       [ 11,   7,   8],
       [111,   7,   8]])
'''
x[1:,1:] = [[7,8],[9,10]]
'''
array([[  1,   2,   9],
       [ 11,   7,   8],
       [111,   9,  10]])
'''
檢視陣列的大小
n.size
將陣列分為兩行五列
n.shape = 2,5
顯示陣列的維度
n.shape
設定陣列的維度,-1 表示自動計算
n.shape = 5,-1
將新陣列設定為呼叫陣列的兩行五列並返回
x = n.reshape(2,5)
x = np.arange(5)
# 將陣列設定為兩行,沒有數的設定為 0
x.resize((2,10))
'''
array([[0, 1, 2, 3, 4, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
'''


# 將 x 陣列的兩行五列形式顯示,不改變 x 的值
np.resize(x,(2,5))
'''
array([[0, 1, 2, 3, 4],
       [0, 0, 0, 0, 0]])
'''
x = np.array([1,4,5,2])
# array([1, 4, 5, 2])

# 返回排序後元素的原下標
np.argsort(x)
# array([0, 3, 1, 2], dtype=int64)
輸出最大值的下標
x.argmax( )
輸出最小值的下標
x.argmin( )
對陣列進行排序
x.sort( )
每個陣列元素對應的正弦值
np.sin(x)
每個陣列元素對應的餘弦值
np.cos(x)
對引數進行四捨五入
np.round(np.cos(x))
對引數進行上入整數 3.3->4
np.ceil(x/3)
# 分段函式
x = np.random.randint(0,10,size=(1,10))
# array([[0, 3, 6, 7, 9, 4, 9, 8, 1, 8]])

# 大於 4 的置為 0
np.where(x > 4,0,1)
# array([[1, 1, 0, 0, 0, 1, 0, 0, 1, 0]])

# 小於 4 的乘 2 ,大於 7 的乘3
np.piecewise(x,[x<4,x>7],[lambda x:x*2,lambda x:x*3])
# array([[ 0,  6,  0,  0, 27,  0, 27, 24,  2, 24]])

資料庫 mysql-connector 基礎
安裝驅動

python -m pip install mysql-connector
導包

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",       # 資料庫主機地址
  user="root",    # 資料庫使用者名稱
  passwd="root"   # 資料庫密碼
)
建立遊標

mycursor = mydb.cursor()
使用 mycursor.execute("sql 語句") 進行執行

mycursor.execute("CREATE DATABASE runoob_db")
指定資料庫名為 runoob_db


mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
建立資料表

mycursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")
檢視當前資料表有哪些

mycursor.execute("SHOW TABLES")
使用 "INT AUTO_INCREMENT PRIMARY KEY" 語句
建立一個主鍵,主鍵起始值為 1,逐步遞增

mycursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
建立表時,新增主鍵

mycursor.execute("CREATE TABLE sites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), url VARCHAR(255))")
插入資料

sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = ("RUNOOB", "https://www.runoob.com")
mycursor.execute(sql, val)
 
mydb.commit()    # 資料表內容有更新,必須使用到該語句
列印 行號

mycursor.rowcount
插入多條語句

sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = [
  ('Google', 'https://www.google.com'),
  ('Github', 'https://www.github.com'),
  ('Taobao', 'https://www.taobao.com'),
  ('stackoverflow', 'https://www.stackoverflow.com/')
]
 
mycursor.executemany(sql, val)
 
mydb.commit()    # 資料表內容有更新,必須使用到該語句
在資料插入後,獲取該條記錄的 ID

mycursor.lastrowid
使用  fetchall() 獲取所有記錄

mycursor.execute("SELECT * FROM sites")
 
myresult = mycursor.fetchall() 
 
for x in myresult:
  print(x)
選取指定資料進行查詢

mycursor.execute("SELECT name, url FROM sites") 

myresult = mycursor.fetchall() 

for x in myresult:
  print(x)
使用 .fetchone() 獲取一條資料

mycursor.execute("SELECT * FROM sites")
 
myresult = mycursor.fetchone()
 
print(myresult)
使用 where 語句

sql = "SELECT * FROM sites WHERE name ='RUNOOB'"
 
mycursor.execute(sql)
 
myresult = mycursor.fetchall()
使用 fetchall 之後,需要使用迴圈進行輸出

for x in myresult:
  print(x)
使用 萬用字元 % 
sql = "SELECT * FROM sites WHERE url LIKE '%oo%'"
使用 %s 防止發生 SQL 注入攻擊

sql = "SELECT * FROM sites WHERE name = %s"
na = ("RUNOOB", )
 
mycursor.execute(sql, na)
排序

使用 ORDER BY 語句,預設升序,關鍵字為 ASC

如果要設定降序排序,可以設定關鍵字 DESC
sql = "SELECT * FROM sites ORDER BY name"
 
mycursor.execute(sql)
降序 DESC

sql = "SELECT * FROM sites ORDER BY name DESC"
 
mycursor.execute(sql)
使用 limit 設定查詢的資料量

mycursor.execute("SELECT * FROM sites LIMIT 3")
limit 指定起始位置 使用 offset

mycursor.execute("SELECT * FROM sites LIMIT 3 OFFSET 1")  
# 0 為 第一條,1 為第二條,以此類推
 
myresult = mycursor.fetchall()
刪除記錄 delete from

sql = "DELETE FROM sites WHERE name = 'stackoverflow'"
 
mycursor.execute(sql)
sql = "DELETE FROM sites WHERE name = %s"
na = ("stackoverflow", )
 
mycursor.execute(sql, na)
更新表中資料  update

sql = "UPDATE sites SET name = 'ZH' WHERE name = 'Zhihu'"
 
mycursor.execute(sql)
sql = "UPDATE sites SET name = %s WHERE name = %s"
val = ("Zhihu", "ZH")
 
mycursor.execute(sql, val)
刪除表 drop table

可以先使用 if exists 判斷是否存在

sql = "DROP TABLE IF EXISTS sites"  # 刪除資料表 sites
 
mycursor.execute(sql)

爬蟲流程(前面發過的文章的合集)鞏固
1.開啟網頁
urllib.request.urlopen('網址')
例:response = urllib.request.urlopen('http://www.baidu.com/') 返回值為 <http.client.HTTPResponse object at 0x00000224EC2C9490>
2.獲取響應頭資訊
urlopen 物件.getheaders()

例:response.getheaders()
返回值為 [('Bdpagetype', '1'), ('Bdqid', '0x8fa65bba0000ba44'),···,('Transfer-Encoding', 'chunked')]
[('頭','資訊')]
3.獲取響應頭資訊,帶引數表示指定響應頭
urlopen 物件.getheader('頭資訊')

例:response.getheader('Content-Type')
返回值為 'text/html;charset=utf-8'
4.檢視狀態碼
urlopen 物件.status

例:response.status
返回值為 200 則表示成功
5.得到二進位制資料,然後轉換為 utf-8 格式
二進位制資料
例:html = response.read()

HTML 資料格式
例:html = response.read().decode('utf-8')
列印輸出時,使用 decode('字符集') 的資料 print(html.decode('utf-8'))
6.儲存 HTML 資料
fp = open('檔名.html','模式 wb')

例:fp = open('baidu.html', 'wb')
fp.write(response.read() 物件)
例:fp.write(html)
7.關閉檔案
open物件.close()

例:fp.close()
8.使用 ssl 進行抓取 https 的網頁
例:
    import ssl
    content = ssl._create_unverified_context()
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}

    request = urllib.request.Request('http://www.baidu.com/', headers = headers)
    response = urllib.request.urlopen(request, context = context)
    這裡的 response 就和上面一樣了
9.獲取碼
response.getcode()

返回值為 200
10.獲取爬取的網頁 url
response.geturl()

返回值為 https://www.baidu.com/
11.獲取響應的報頭資訊
response.info()
12.儲存網頁
urllib.request.urlretrieve(url, '檔名.html')

例:urllib.request.urlretrieve(url, 'baidu.html')
13.儲存圖片
urllib.request.urlretrieve(url, '圖片名.jpg')

例:urllib.request.urlretrieve(url, 'Dog.jpg')
其他字元(如漢字)不符合標準時,要進行編碼
14.除了-._/09AZaz 都會編碼
urllib.parse.quote()
例:
    Param = "全文檢索:*"
    urllib.parse.quote(Param)
返回值為 '%E5%85%A8%E6%96%87%E6%A3%80%E7%B4%A2%3A%2A'
15.會編碼 / 斜線(將斜線也轉換為 %.. 這種格式)

urllib.parse.quote_plus(Param)
16.將字典拼接為 query 字串 如果有中文,進行url編碼
dic_object = {
    'user_name':'張三',
    'user_passwd':'123456'
}
urllib.parse.urlencode(dic_object)

返回值為 'user_name=%E5%BC%A0%E4%B8%89&user_passwd=123456'
17.獲取 response 的行
url = 'http://www.baidu.com'
response = urllib.request.urlopen(url)

response.readline()
18.隨機獲取請求頭(隨機包含請求頭資訊的列表)
user_agent = [
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv2.0.1) Gecko/20100101 Firefox/4.0.1",
        "Mozilla/5.0 (Windows NT 6.1; rv2.0.1) Gecko/20100101 Firefox/4.0.1",
        "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
        "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"
]

ua = random.choice(user_agent)
headers = {'User-Agent':ua}
19.對輸入的漢字進行 urlencode 編碼
urllib.parse.urlencode(字典物件)

例:
chinese = input('請輸入要查詢的中文詞語:')

wd = {'wd':chinese}
wd = urllib.parse.urlencode(wd)

返回值為 'wd=%E4%BD%A0%E5%A5%BD'
20.常見分頁操作
for page in range(start_page, end_page + 1):
        pn = (page - 1) * 50
21.通常會進行拼接字串形成網址

例:fullurl = url + '&pn=' + str(pn)
22.進行拼接形成要儲存的檔名

例:filename = 'tieba/' + name + '貼吧_第' + str(page) + '頁.html'
23.儲存檔案

with open(filename,'wb') as f:
    f.write(reponse.read() 物件)
24.headers 頭資訊可以刪除的有

cookie、accept-encoding、accept-languag、content-length\connection\origin\host
25.headers 頭資訊不可以刪除的有

Accept、X-Requested-With、User-Agent、Content-Type、Referer
26.提交給網頁的資料 formdata

formdata = {
    'from':'en',
    'to':'zh',
    'query':word,
    'transtype':'enter',
    'simple_means_flag':'3'
}
27.將formdata進行urlencode編碼,並且轉化為bytes型別

formdata = urllib.parse.urlencode(formdata).encode('utf-8')
28.使用 formdata 在 urlopen() 中

response = urllib.request.urlopen(request, data=formdata)
29.轉換為正確資料(導包 json)

read -> decode -> loads -> json.dumps

通過read讀取過來為位元組碼
data = response.read()

將位元組碼解碼為utf8的字串
data = data.decode('utf-8')

將json格式的字串轉化為json物件
obj = json.loads(data)

禁用ascii之後,將json物件轉化為json格式字串
html = json.dumps(obj, ensure_ascii=False)

json 物件通過 str轉換後 使用 utf-8 字符集格式寫入
儲存和之前的方法相同

with open('json.txt', 'w', encoding='utf-8') as f:
    f.write(html)
30.ajax請求自帶的頭部

'X-Requested-With':'XMLHttpRequest'
31.豆瓣預設都得使用https來進行抓取,所以需要使用ssl模組忽略證書
例:
url = 'http://movie.douban.com/j/chart/top_list?type=24&interval_id=100%3A90&action='

page = int(input('請輸入要獲取頁碼:'))
start = (page - 1) * 20
limit = 20

key = {
    'start':start,
    'limit':limit
}

key = urllib.parse.urlencode(key)
url = url + '&' + key
headers = {
    'X-Requested-With':'XMLHttpRequest',
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
}

request = urllib.request.Request(url, headers=headers)

# context = ssl._create_unverified_context()
response = urllib.request.urlopen(request)

jsonret = response.read()

with open('douban.txt', 'w', encoding='utf-8') as f:
    f.write(jsonret.decode('utf-8'))
print('over')
32.建立處理 http 請求的物件

http_handler = urllib.request.HTTPHandler()
33.處理 https 請求

https_handler = urllib.request.HTTPSHandler()
34.建立支援http請求的opener物件

opener = urllib.request.build_opener(http_handler)
35.建立 reponse 物件
例:opener.open(Request 物件)

request = urllib.request.Request('http://www.baidu.com/')
reponse = opener.open(request)

進行儲存
with open('檔名.html', 'w', encoding='utf-8') as f:
    f.write(reponse.read().decode('utf-8'))
36.代理伺服器

http_proxy_handler = urllib.request.ProxyHandler({'https':'ip地址:埠號'})

例:http_proxy_handler = urllib.request.ProxyHandler({'https':'121.43.178.58:3128'})
37.私密代理伺服器(下面的只是一個例子,不一定正確)

authproxy_handler = urllib.request.ProxyHandler({"http" : "user:password@ip:port"})
38.不使用任何代理

http_proxy_handler = urllib.request.ProxyHandler({})
39.使用了代理之後的 opener 寫法
opener = urllib.request.build_opener(http_proxy_handler)
40.response 寫法
response = opener.open(request)
41.如果訪問一個不存在的網址會報錯

urllib.error.URLError
42.HTTPError(是URLError的子類)

例:
try:

    urllib.request.urlopen(url)

except urllib.error.HTTPError as e:
    print(e.code)
    print(e.reason)

except urllib.error.URLError as e:
    print(e)
43.使用 CookieJar 建立一個 cookie 物件,儲存 cookie 值

import http.cookiejar
cookie = http.cookiejar.CookieJar( )
44.通過HTTPCookieProcessor構建一個處理器物件,用來處理cookie

cookie_handler = urllib.request.HTTPCookieProcessor(cookie)

opener 的寫法
opener = urllib.request.build_opener(cookie_handler)
45.使用 r'\x' 消除轉義
\d 表示轉義字元  r'\d' 表示 \d
46.設定 正則模式
pattern = re.compile(r'規則', re.xxx )
pattern = re.compile(r'i\s(.*?),')

例:pattern = re.compile(r'LOVE', re.I)
使用 pattern 進行呼叫匹配

47.match 只匹配開頭字元

pattern.match('字串'[,起始位置,結束位置])

例:m = pattern.match('i love you', 2, 6)
返回值為 <re.Match object; span=(2, 6), match='love'>
48. search 從開始匹配到結尾,返回第一個匹配到的
pattern.search('字串')

例:m = pattern.search('i love you, do you love me, yes, i love')
返回值為 <re.Match object; span=(2, 6), match='love'>
49.findall 將匹配到的都放到列表中
pattern.findall('字串')

例:m = pattern.findall('i love you, do you love me, yes, i love')
返回值為 ['love', 'love', 'love']
50.split 使用匹配到的字串對原來的資料進行切割
pattern.split('字串',次數)

例:m = pattern.split('i love you, do you love me, yes, i love me', 1)
返回值為 ['i ', ' you, do you love me, yes, i love me']

例:m = pattern.split('i love you, do you love me, yes, i love me', 2)
返回值為 ['i ', ' you, do you ', ' me, yes, i love me']

例:m = pattern.split('i love you, do you love me, yes, i love me', 3)
返回值為 ['i ', ' you, do you ', ' me, yes, i ', ' me']
51.sub 使用新字串替換匹配到的字串的值,預設全部替換
pattern.sub('新字串','要匹配字串'[,次數])
注:返回的是字串

例:
string = 'i love you, do you love me, yes, i love me'
m = pattern.sub('hate', string, 1)
m 值為 'i hate you, do you love me, yes, i love me'
52.group 匹配組
m.group() 返回的是匹配都的所有字元
m.group(1) 返回的是第二個規則匹配到的字元

例:
string = 'i love you, do you love me, yes, i love me'
pattern = re.compile(r'i\s(.*?),')
m = pattern.match(string)

m.group()
返回值為 'i love you,'
m.group(1)
返回值為 'love you'
53.匹配標籤

pattern = re.compile(r'<div class="thumb">(.*?)<img src=(.*?) alt=(.*?)>(.*?)</div>', re.S)
54.分離出檔名和副檔名,返回二元組
os.path.splitext(引數)

例:
獲取路徑
image_path = './qiushi'

獲取字尾名
extension = os.path.splitext(image_url)[-1]
55.合併多個字串
os.path.join()

圖片路徑
image_path = os.path.join(image_path, image_name + extension)

儲存檔案
urllib.request.urlretrieve(image_url, image_path)
56.獲取 a 標籤下的 href 的內容

pattern = re.compile(r'<a href="(.*?)" class="main_14" target="_blank">(.*?)</a>', re.M)
57.href 中有中文的需要先進行轉碼,然後再拼接

smile_url = urllib.parse.quote(smile_url)
smile_url = 'http://www.jokeji.cn' + smile_url
58.匯入 etree
from lxml import etree
59.例項化一個 html 物件,DOM模型
etree.HTML
(通過requests庫的get方法或post方法獲取的資訊 其實就是 HTML 程式碼)

例:html_tree = etree.HTML(text)
返回值為 <Element html at 0x26ee35b2400>

例:type(html_tree)
<class 'lxml.etree._Element'>
60.查詢所有的 li 標籤
html_tree.xpath('//li')
61.獲取所有li下面a中屬性href為link1.html的a

result = html_tree.xpath('//標籤/標籤[@屬性="值"]')
例:result = html_tree.xpath('//li/a[@href="link.html"]')
62.獲取最後一個 li 標籤下 a 標籤下面的 href 值

result = html_tree.xpath('//li[last()]/a/@href')
63.獲取 class 為 temp 的結點

result = html_tree.xpath('//*[@class = "temp"]')
64.獲取所有 li 標籤下的 class 屬性

result = html_tree.xpath('//li/@class')
65.取出內容
[0].text

例:result = html_tree.xpath('//li[@class="popo"]/a')[0].text
例:result = html_tree.xpath('//li[@class="popo"]/a/text()')
66.將 tree 物件轉化為字串

etree.tostring(etree.HTML物件).decode('utf-8')

67.動態儲存圖片,使用url後幾位作為檔名
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request)
html_tree = etree.HTML(html)
img_list = html_tree.xpath('//div[@class="box picblock col3"]/div/a/img/@src2')
for img_url in img_list:
    # 定製圖片名字為url後10位
    file_name = 'image/' + img_url[-10:]
    load_image(img_url, file_name)
load_image內容:
def load_image(url, file_name):
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    }
    request = urllib.request.Request(url, headers=headers)
    response = urllib.request.urlopen(request)
    image_bytes = response.read()

    with open(file_name, 'wb') as f:
        f.write(image_bytes)
    print(file_name + '圖片已經成功下載完畢')

例:
def load_page(url):
    headers = {
        #'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    }
    print(url)
    # exit()
    request = urllib.request.Request(url, headers=headers)
    response = urllib.request.urlopen(request)
    html = response.read()

    # 這是專業的圖片網站,使用了懶載入,但是可以通過原始碼來進行檢視,並且重新寫xpath路徑
    with open('7image.html', 'w', encoding='utf-8') as f:
        f.write(html.decode('utf-8'))
    exit()

    # 將html文件解析問DOM模型
    html_tree = etree.HTML(html)
    # 通過xpath,找到需要的所有的圖片的src屬性,這裡獲取到的
    img_list = html_tree.xpath('//div[@class="box picblock col3"]/div/a/img/@src2')
    for img_url in img_list:
        # 定製圖片名字為url後10位
        file_name = 'image/' + img_url[-10:]
        load_image(img_url, file_name)

def load_image(url, file_name):
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    }
    request = urllib.request.Request(url, headers=headers)
    response = urllib.request.urlopen(request)
    image_bytes = response.read()

    with open(file_name, 'wb') as f:
        f.write(image_bytes)
    print(file_name + '圖片已經成功下載完畢')
def main():
    start = int(input('請輸入開始頁面:'))
    end = int(input('請輸入結束頁面:'))
    url = 'http://sc.chinaz.com/tag_tupian/'
    for page in range(start, end + 1):
        if page == 1:
            real_url = url + 'KaTong.html'
        else:
            real_url = url + 'KaTong_' + str(page) + '.html'
        load_page(real_url)
        print('第' + str(page) + '頁下載完畢')

if __name__ == '__main__':
    main()
68.懶圖片載入案例
例:
import urllib.request
from lxml import etree
import json

def handle_tree(html_tree):
    node_list = html_tree.xpath('//div[@class="detail-wrapper"]')
    duan_list = []
    for node in node_list:
        # 獲取所有的使用者名稱,因為該xpath獲取的是一個span列表,然後獲取第一個,並且通過text屬性得到其內容
        user_name = node.xpath('./div[contains(@class, "header")]/a/div/span[@class="name"]')[0].text
        # 只要涉及到圖片,很有可能都是懶載入,所以要右鍵檢視網頁原始碼,才能得到真實的連結
        # 由於這個獲取的結果就是屬性字串,所以只需要加上下標0即可
        face = node.xpath('./div[contains(@class, "header")]//img/@data-src')[0]
        # .代表當前,一個/表示一級子目錄,兩個//代表當前節點裡面任意的位置查詢
        content = node.xpath('./div[@class="content-wrapper"]//p')[0].text
        zan = node.xpath('./div[@class="options"]//li[@class="digg-wrapper "]/span')[0].text
        item = {
            'username':user_name,
            'face':face,
            'content':content,
            'zan':zan,
        }
        # 將其存放到列表中
        duan_list.append(item)

    # 將列表寫入到檔案中
    with open('8duanzi.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(duan_list, ensure_ascii=False) + '\n')
    print('over')

def main():
    # 爬取百度貼吧,不能加上headers,加上headers爬取不下來
    url = 'http://neihanshequ.com/'
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    }
    request = urllib.request.Request(url, headers=headers)
    response = urllib.request.urlopen(request)
    html_bytes = response.read()

    # fp = open('8tieba.html', 'w', encoding='utf-8')
    # fp.write(html_bytes.decode('utf-8'))
    # fp.close()
    # exit()

    # 將html位元組串轉化為html文件樹
    # 文件樹有xpath方法,文件節點也有xpath方法 
    # 【注】不能使用位元組串轉化為文件樹,這樣會有亂碼
    html_tree = etree.HTML(html_bytes.decode('utf-8'))

    handle_tree(html_tree)


if __name__ == '__main__':
    main()
69.  . / 和 // 在 xpath 中的使用
.代表當前目錄
/ 表示一級子目錄
// 代表當前節點裡面任意的位置
70.獲取內容的示範
獲取內容時,如果為字串,則不需要使用 text 只需要寫[0]
face = node.xpath('./div[contains(@class, "header")]//img/@data-src')[0]

div 下 class 為 "content-wrapper" 的所有 p 標籤內容
content = node.xpath('./div[@class="content-wrapper"]//p')[0].text

div 下 class 為 "options" 的所有 li 標籤下 class為 "digg-wrapper" 的所有 span 標籤內容

zan = node.xpath('./div[@class="options"]//li[@class="digg-wrapper"]/span')[0].text
71.將json物件轉化為json格式字串

f.write(json.dumps(duan_list, ensure_ascii=False) + '\n')
72.正則獲取 div 下的內容

1.獲取 div 到 img 之間的資料
2.img 下 src 的資料
3.img 下 alt 的資料
4.一直到 div 結束的資料

pattern = re.compile(r'<div class="thumb">(.*?)<img src=(.*?) alt=(.*?)>(.*?)</div>', re.S)
pattern.方法 ,參考上面的正則
73.帶有引數的 get 方式

import requests
params = {
    'wd':'中國'
}
r = requests.get('http://www.baidu.com/s?', headers=headers, params=params)

requests.get 還可以新增 cookie 引數
74.設定編碼
r.encoding='utf-8
75.檢視所有頭資訊
r.request.headers
76.在 requests.get 方法中 url,params,headers,proxies 為引數

url 網址  params 需要的資料 headers 頭部 proxies 代理
77.通過 Session 物件,傳送請求
s = requests.Session()

78.傳送請求
s.post(url,data,headers)

79.接收請求
s.get(url[,proxies])

80.當返回為 json 樣式時
例:
city = input('請輸入要查詢的城市:')
params = {
    'city':city
}
r = requests.get(url, params=params)
r.json() 會打印出響應的內容

81.BeautifulSoup 建立物件
from bs4 import BeautifulSoup
soup = BeautifulSoup(open(url,encoding='utf-8),'lxml')

82.查詢第一個<title> 標籤
soup.title
返回值為 <title>三國猛將</title>

83.查詢第一個 a 標籤
soup.a
返回值為 <a class="aa" href="http://www.baidu.com" title="baidu">百度</a>

84.查詢第一個 ul 標籤
soup.ul

85.檢視標籤名字
a_tag = soup.a
a_tag.name
返回值為 a

86.檢視標籤內容
a_tag.attrs
返回值為 {'href': 'http://www.baidu.com', 'title': 'baidu', 'class': ['aa']}

87.獲取找到的 a 標籤的 href 內容(第一個 a)
soup.a.get('href')
返回值為 http://www.baidu.com

88.獲取 a 標籤下的 title 屬性(第一個 a)
soup.a.get('title')
返回值為 baidu

89.檢視 a 標籤下的內容
soup.標籤.string 標籤還可以是 head、title等
soup.a.string
返回值為 百度

90.獲取 p 標籤下的內容
soup.p.string

91.檢視 div 的內容,包含 '\n'
soup.div.contents
返回值為
['\n', <div class="div">
<a class="la" href="www.nihao.com">你好</a>
</div>, '\n', <div>
<a href="www.hello.com">世界</a>
</div>, '\n']

92.檢視使用的字符集
soup.div.contents[1]
返回值為 <meta charset="utf-8"/>

93.檢視body的子節點
soup.標籤.children
例:soup.body.children
返回值是一個迭代物件,需要遍歷輸出
返回值為 <list_iterator object at 0x0000021863886C10>
for child in soup.body.children:
    print(child)
返回值為 body 中的所有內容

94.檢視所有的子孫節點
soup.標籤.descendants
例:soup.div.descendants
返回值為
<div class="div">
<a class="la" href="www.nihao.com">你好</a>
</div>
<a class="la" href="www.nihao.com">你好</a>
你好

95.檢視所有的 a 標籤
soup.find_all('a')
返回值為 包含所有的 a 標籤的列表

96.檢視 a 標籤中第二個連結的內容
soup.find_all('a')[1].string

97.檢視 a 標籤中第二個連結的href值
soup.find_all('a')[1].href

98.將 re 正則嵌入進來,找尋所有以 b 開頭的標籤
soup.findall(re.compile('^b'))
返回值為 <body>標籤 <b>

99.找到所有的 a 標籤和 b 標籤
soup.findall(re.compile(['a','b']))
返回值為 <a> 和 <b> 標籤

100.通過標籤名獲取所有的 a 標籤
soup.select('a')
返回值為 所有的 <a> 標籤

101.通過 類名 獲取標籤(在 class 等於的值前面加 .)
soup.select('.aa')
返回值為 class='aa' 的標籤

102.通過 id 名獲取標籤(在 id 等於的值前面加 #)
soup.select('#wangyi')
返回值為 id='wangyi'的標籤

103.檢視 div 下 class='aa' 的標籤
soup.select('標籤 .class 等於的值')
soup.select('div .aa')

104.檢視 div 下,第一層 class='aa' 的標籤
soup.select('.標籤名 > .class= 的值')
soup.select('.div > .la')

105.根據屬性進行查詢,input 標籤下class為 haha 的標籤
soup.select('input[class="haha"]')

例:
import requests
from bs4 import BeautifulSoup
import json
import lxml

def load_url(jl, kw):
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    }

    url = 'http://sou.zhaopin.com/jobs/searchresult.ashx?'
    params = {
        'jl':jl,
        'kw':kw,
    }
    # 自動完成轉碼,直接使用即可
    r = requests.get(url, params=params, headers=headers)

    handle_data(r.text)

def handle_data(html):
    # 建立soup物件
    soup = BeautifulSoup(html, 'lxml')
    # 查詢職位名稱
    job_list = soup.select('#newlist_list_content_table table')
    # print(job_list)
    jobs = []
    i = 1
    for job in job_list:
        # 因為第一個table只是表格的標題,所以要過濾掉
        if i == 1:
            i = 0
            continue
        item = {}
        # 公司名稱
        job_name = job.select('.zwmc div a')[0].get_text()

        # 職位月薪
        company_name = job.select('.gsmc a')[0].get_text()
        # 工作地點
        area = job.select('.gzdd')[0].get_text()

        # 釋出日期
        time = job.select('.gxsj span')[0].get_text()
        # 將所有資訊新增到字典中
        item['job_name'] = job_name
        item['company_name'] = company_name
        item['area'] = area
        item['time'] = time
        jobs.append(item)

    # 將列表轉化為json格式字串,然後寫入到檔案中
    content = json.dumps(jobs, ensure_ascii=False)
    with open('python.json', 'w', encoding='utf-8') as f:
        f.write(content)
    print('over')

def main():
    # jl = input('請輸入工作地址:')
    # kw = input('請輸入工作職位:')
    load_url(jl='北京', kw='python')

if __name__ == '__main__':
    main()

106.將字典進行 json 轉換為
import json
str_dict = {"name":"張三", "age":55, "height":180}
print(json.dumps(str_dict, ensure_ascii=False))
使用 ensure_ascii 輸出則為 utf-8 編碼

107.讀取轉換的物件,(注意 loads 和 load 方法)
json.loads(json.dumps 物件)
string = json.dumps(str_dict, ensure_ascii=False)
json.loads(string)
{"name":"張三", "age":55, "height":180}

108.將物件序列化之後寫入檔案
json.dump(字典物件,open(檔名.json,'w',encoding='utf-8,ensure_ascii=False))
json.dump(str_dict, open('jsontest.json', 'w', encoding='utf-8'), ensure_ascii=False)

109.轉換本地的 json 檔案轉換為 python 物件
json.load(open('檔名.json',encoding='utf-8))

110.jsonpath 示例:
book.json檔案
{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    }
}

import json
import jsonpath

obj = json.load(open('book.json', encoding='utf-8'))

所有book
book = jsonpath.jsonpath(obj, '$..book')
print(book)

所有book中的所有作者
authors = jsonpath.jsonpath(obj, '$..book..author')
print(authors)

book中的前兩本書   '$..book[:2]'
book中的最後兩本書 '$..book[-2:]'
book = jsonpath.jsonpath(obj, '$..book[0,1]')
print(book)

所有book中,有屬性isbn的書籍
book = jsonpath.jsonpath(obj, '$..book[?(@.isbn)]')
print(book)

所有book中,價格小於10的書籍
book = jsonpath.jsonpath(obj, '$.store.book[?(@.price<10)]')
print(book)

111.requests.get 方法的流程
r = requests.get('https://www.baidu.com/').content.decode('utf-8')
從狀態碼到 二進位制碼到 utf-8 編碼

112.對 soup 物件進行美化
html = soup.prettify()
<title>
   百度一下,你就知道
  </title>

113.將內容 string 化
html.xpath('string(//*[@id="cnblogs_post_body"])')

114.獲取屬性
soup.p['name']

115.巢狀選擇
soup.head.title.string

116.獲取父節點和祖孫節點
soup.a.parent
list(enumerate(soup.a.parents))

117.獲取兄弟節點
soup.a.next_siblings
list(enumerate(soup.a.next_siblings))

soup.a.previous_siblings
list(enumerate(soup.a.previous_siblings))

118.按照特定值查詢標籤
查詢 id 為 list-1 的標籤
soup.find_all(attrs={'id': 'list-1'})
soup.find_all(id='list-1')

119.返回父節點
find_parents()返回所有祖先節點
find_parent()返回直接父節點

120.返回後面兄弟節點
find_next_siblings()返回後面所有兄弟節點
find_next_sibling()返回後面第一個兄弟節點。

121.返回前面兄弟節點
find_previous_siblings()返回前面所有兄弟節點
find_previous_sibling()返回前面第一個兄弟節點。

122.返回節點後符合條件的節點
find_all_next()返回節點後所有符合條件的節點
find_next()返回第一個符合條件的節點

123.返回節點前符合條件的節點
find_all_previous()返回節點前所有符合條件的節點
find_previous()返回第一個符合條件的節點

124.requests 的請求方式
requests.post(url)
requests.put(url)
requests.delete(url)
requests.head(url)
requests.options(url)

125.GET請求
response = requests.get(url)
print(response.text)

126.解析 json
response.json()
json.loads(response.text)

127.傳送 post 請求
response = requests.post(url, data=data, headers=headers)
response.json()

128.檔案上傳
在 post 方法內部新增引數 files 字典引數
import requests
files = {'file': open('favicon.ico', 'rb')}
response = requests.post("http://httpbin.org/post", files=files)
print(response.text)

129.獲取 cookie
response.cookie
返回值是 字典物件
for key, value in response.cookies.items():
    print(key + '=' + value)

130.模擬登入
requests.get('http://httpbin.org/cookies/set/number/123456789')
response = requests.get('http://httpbin.org/cookies')

131.帶有 Session 的登入
s = requests.Session()
s.get('http://httpbin.org/cookies/set/number/123456789')
response = s.get('http://httpbin.org/cookies')

132.證書驗證
urllib3.disable_warnings()
response = requests.get('https://www.12306.cn', verify=False)

response = requests.get('https://www.12306.cn', cert=('/path/server.crt', '/path/key'))

133.超時設定
from requests.exceptions import ReadTimeout
response = requests.get("http://httpbin.org/get", timeout = 0.5)

response = urllib.request.urlopen(url, timeout=1)

134.認證設定
from requests.auth import HTTPBasicAuth
r = requests.get('http://120.27.34.24:9001', auth=HTTPBasicAuth('user', '123'))

r = requests.get('http://120.27.34.24:9001', auth=('user', '123'))

135.異常處理
超時 ReadTimeout
連接出錯 ConnectionError
錯誤 RequestException

136.URL 解析
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')

result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https')


result = urlparse('http://www.baidu.com/index.html;user?id=5#comment',allow_fragments=False)

136.urllib.parse.urlunparse
data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data))

http://www.baidu.com/index.html;user?a=6#comment

137.合併 url
urllib.parse.urljoin
urljoin('http://www.baidu.com', 'FAQ.html')
http://www.baidu.com/FAQ.html
urljoin('www.baidu.com#comment', '?category=2')
www.baidu.com?category=2

matplotlib示例
plt.plot 內只有一個列表示例


import matplotlib.pyplot as plt
lst = [4.53,1.94,4.75,0.43,2.02,1.22,2.13,2.77]
plt.plot(lst)
plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號

plt.title("使用一行列表進行繪製折線圖")
plt.show()

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號

x = range(0,8)
y1 = [4.53,1.74,4.55,0.03,2.12,1.22,2.43,2.77]
y2 = [2.38, 4.23,1.49,2.75,3.73,4.90,0.13,1.29]
plt.plot(x,y1,'b-1',x,y2,'m:o')
plt.xlabel('x軸')
plt.ylabel('y軸')
plt.title("繪製兩個折線圖示例")
plt.show()
設定顯示樣式

plt.plot(x,y1,'b-1',x,y2,'m:o')
設定中文標籤

plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False #用來正常顯示負號
import numpy as np
import matplotlib.pyplot as plt
with open("haidian.csv","r",encoding = 'utf-8') as f:
    data = np.loadtxt(f,str,delimiter = ',')
x = data[:,1][::10]
y = data[:,4][::10]
plt.plot(x,y,'g-o')
plt.xlabel("時間",fontproperties = 'SimHei')
plt.ylabel("溫度",fontproperties = 'SimHei')
plt.title("海淀地區20日溫度趨勢圖",fontproperties = 'FangSong',fontsize = 20)
plt.xticks(rotation=90) 
# x 軸旋轉角度
plt.show()

設定 x y 標籤時,指定使用的字型
fontproperties = 'SimHei'

plt.xlabel("時間",fontproperties = 'SimHei')
plt.ylabel("溫度",fontproperties = 'SimHei')
開啟 csv 檔案時,使用 np.loadtxt 進行讀取
先使用 with open 開啟檔案,然後使用 np.loadtxt 進行讀取
np.loadtxt(f,str,delimiter = ',')
提取過來的資料時 numpy.str_型別,使用時可以使用str進行轉換

with open("haidian.csv","r",encoding = 'utf-8') as f:
    data = np.loadtxt(f,str,delimiter = ',')
直方圖 hist 引數

data:必選引數,繪圖資料
bins:直方圖的長條形數目,可選項,預設為10
normed:是否將得到的直方圖向量歸一化,可選項
預設為0,代表不歸一化,顯示頻數
normed=1 表示歸一化,顯示頻率
facecolor:長條形的顏色
edgecolor:長條形邊框的顏色
alpha:透明度
一張圖顯示兩個直方圖示例

from matplotlib import pyplot as plt 
x =  [5,8,10] 
y =  [12,16,6] 
x2 =  [6,9,11] 
y2 =  [6,15,7] 
plt.bar(x, y, align =  'center',label = 'x') 
plt.bar(x2, y2, color =  'g', align =  'center',label = 'x2') 
plt.title('直方圖圖示') 
plt.ylabel('Y軸') 
plt.xlabel('X軸') 
plt.legend()
plt.show()
使用 plt.subplot(2,1) 繪製子圖

通過子圖設定標籤

ax[0].hist(avg_wd,bins = 15,alpha=0.7)
ax[0].set(title=u"時間和溫度的關係圖",ylabel=u"溫度") # 設定標題

ax[1].hist(avg_sd,bins = 15,alpha=0.7)
ax[1].set_title('時間和溼度的關係圖')
ax[1].set(title=u"14-28日煙臺時間和溼度的關係圖",ylabel=u"溼度") # 設定標題

matplotlib顏色線條及繪製直線

plt.axhline(y=0,ls=":",c="yellow")#新增水平直線
plt.axvline(x=4,ls="-",c="green")#新增垂直直線

matplotlib繪製子圖
fig,subs = plt.subplots(2,2)

subs[0][0].plot(data_math_C1)
subs[0][0].set_title('C_1 曲線')

subs[0][1].plot(data_math_C2)
subs[0][1].set_title('C_2 曲線')

subs[1][0].plot(data_math_C3)
subs[1][0].set_title('C_3 曲線')

subs[1][1].plot(data_math_C4)
subs[1][1].set_title('C_4 曲線')

plt.show()

下載資料到csv中(亂碼),使用numpy , pandas讀取失敗 解決方案
讀取資料,下載資料到 csv 檔案中
allUniv 列表型別[[...],[...]]
字符集編碼使用 utf-8-sig 


with open('檔名.csv','w',newline='',encoding='utf-8-sig') as fout:
    write = csv.writer(fout)
    columns = ['文字', '文字', '文字',
               '文字', '文字', '文字']
    write.writerow(columns)
    for row in allUniv:
        write.writerow(row)
讀取 csv 檔案

一定要使用 pd.read_csv 進行讀取


data = pd.read_csv('檔名.csv')
print(data[:5])

檢視一個數所有的因子及因子的和
def factor(n):
    nums = [ ]
    for i in range(1,n+1):
        if n % i == 0:
            nums.append(i)
    print(n,"的因子有:",nums)
    print("所有因子的和為: ",sum(nums))
while True:
    num = int(input("請輸入 100 到 1000 之間的數"))
    if not 100 <= num <= 1000:
        print("請輸入正確數值")
        continue
    factor(num)
    break


輸入 1,2,4,5,78 返回 (1, 78, 2, 4, 5, 90) 返回形式:最小值 最大值 其餘值 及 總和
def min_max_sum(num):
    num = list(num)
    Min = min(num)
    Max = max(num)
    Sum = sum(num)
    num.remove(Min)
    num.remove(Max)
    tup = []
    tup.append(Min)
    tup.append(Max)
    for i in num:
        tup.append(i)
    tup.append(Sum)
    tup = tuple(tup)
    print(tup)
    return Min,Max,Sum

num = tuple(int(i) for i in input().split(','))

min_max_sum(num)

1000以內能被3或5整除但不能被10整除的數的個數為

dic = {'0':0}
for i in range(1000):
    if i % 3 == 0 and i %5 == 0 and i % 10 != 0:
        dic['0'] += 1
print("1000以內能被3或5整除但不能被10整除的數的個數為:",dic['0'])
輸入數字判斷是否是偶數,輸出兩個質數的和為該偶數的值


nums = []
lst = [i for i in range(101)]
l = []
for j in range(2,101):
    # 將質數加入到 l 中
    temp = 1
    for i in range(2,j-1):
        if lst[j] % i == 0:
            temp = 0
    if temp != 0:
        l.append(lst[j])

while True:
    num = int(input("輸入 0 表示終止"))
    if num == 0:
        # 輸入為 0 退出迴圈
        break
    nums.append(num)

for c in nums:
    if c % 2 == 0:
        # 如果為偶數
        for i in l:
            # l 是質數的集合
            if c - i in l:
                print("{}={}+{}".format(c, i, c - i))
                break
    else:
        print("{0} is odd number!".format(c))

十進位制轉換為其他進位制(不使用format)
base = [str(x) for x in range(10)] + [chr(x) for x in range(ord('A'), ord('A') + 6)]
# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']

def dec2bin(string_num):
    '''十進位制轉換為 二進位制'''
    num = int(string_num)
    # 轉換為 整數
    mid = []
    while True:
        if num == 0: break
        # 如果輸入的十進位制為 0 則退出
        num, rem = divmod(num, 2)
        # num 為 num / 2 的值
        # rem 為 餘數
        mid.append(base[rem])
        # 將餘數新增到 mid 中
    return ''.join([str(x) for x in mid[::-1]])

def dec2oct(string_num):
    '''轉換為 八進位制'''
    num = int(string_num)
    # 轉換為 整數
    mid = []
    while True:
        if num == 0: break
        num, rem = divmod(num, 8)
        # num 為 num / 8 的值
        # rem 為 餘數
        mid.append(base[rem])
        # 將餘數新增到 mid 中
    return ''.join([str(x) for x in mid[::-1]])


def dec2hex(string_num):
    '''轉換為 十六進位制'''
    num = int(string_num)
    # 轉換為 整數
    mid = []
    while True:
        if num == 0: break
        num, rem = divmod(num, 16)
        # num 為 num / 16 的值
        # rem 為 餘數
        mid.append(base[rem])
        # 將餘數新增到 mid 中
    return ''.join([str(x) for x in mid[::-1]])



num = float(input())
# 讓使用者輸入數字

print(dec2bin(num),dec2oct(num),dec2hex(num))
# 輸出 十進位制轉為 2 ,8 ,16 進位制之後的數

字典元組列表常用方法


啟發:
1.可以使用系統給出的方法,就不要自己去建立判斷,效率可能會降低很多
2.使用一個變數不能解決問題,那就建立多個變數
3.找準資料型別,只要資料是這種資料型別,那麼它就具有這個資料型別應該具有的方法,如果沒有你需要的,那麼就進行強制轉換.
4.使用字典儲存值,可以將兩個序列物件的格式進行自定義


dict_xy = dict(zip(df['名稱'],df['名稱']))
# 將資料存為字典結構
for key,value in dict_xy.items():
    # 對字典進行遍歷
    dict_xy[key] = float(value.split("億")[0])
    # 去掉多餘數目
print(dict_xy)

matplotlib 設定x軸斜體

plt.xticks(rotation = 45)


sorted(字典名.items(), key=lambda x: x[1])

x = a[a['列名'] == 值]['列名']
y = a[a['列名'] == 值]['列名']

dic_xy = dict(zip(x,y))
lst_xy = sorted(dic_xy.items(), key=lambda x: x[1],reverse = True)
print(lst_xy)
dic = {}
for index in range(10):
    dic[lst_xy[index][0]] = lst_xy[index][1]
print(dic)

終於,我還是對自己的部落格下手了

爬取自己部落格曾經發布過的所有標題
import csv
import requests
from bs4 import BeautifulSoup
# https://www.cnblogs.com/hany-postq473111315/
# https://www.cnblogs.com/hany-postq473111315/default.html?page=2

for num in range(1,44):
    url = 'https://www.cnblogs.com/hany-postq473111315/default.html?page=' + str(num)
    response = requests.get(url)
    response.raise_for_status()
    response.encoding = response.apparent_encoding

    html = response.text
    soup = BeautifulSoup(html, "html.parser")
    try:
        for i in range(50):
            # print(soup.find_all('a',attrs={'class':'postTitle2'})[i].text.strip('\n').strip())
            with open("部落格園標題.txt", "a+") as f:
                f.write(soup.find_all('a',attrs={'class':'postTitle2'})[i].text.strip('\n').strip() + '\n')
                # 向檔案寫入內容
            print("爬取結束,並存入檔案")
    except:
        pass

獲取列表中出現的值,並按降序進行排列
string = input().split()
dic = {}
for i in string:
    dic[i] = dic.get(i,0) + 1

dic = sorted(dic.items(), key=lambda x: x[1],reverse=True)

for key,value in dic:
    print(key,":",value)

flask的第一次嘗試
from flask import Flask

app = Flask(__name__)
@app.route('/')
def hello_world():
    return "Hello Flask"
@app.route('/index')
def index():
    return "Hello Index"

if __name__ == "__main__":
    # app.run()
    app.run(debug=True)



感悟:

從 flask 中匯入 Flask 後,
from flask import Flask 

建立一個 app 
app = Flask(__name__)

使用的網頁路徑寫在 @app.route(" 路徑位置 ") 中
@app.route("/")
表示根路徑
@app.route("/index")
表示 index 網頁

在使用了路徑之後,在路徑的正下方加入 def 建立該路徑對應的函式
def index():
    return "Hello Index" 
return 後面的內容會返回到網頁上

使用 app.run() 可以執行
if __name__ == '__main__':
    app.run(debug = True)
使用 debug 進行除錯

條件表示式


ages = 20
ticketPrice = 20 if ages >= 16 else 10



count = 8
print( count if count % 10 == 0 else "不能被10整除")


成立條件時執行的語句 if 條件 else 不成立時執行的語句

安裝fiddler 谷歌外掛

移動 .crx 外掛無法安裝問題

解決方案:
修改後綴名為 .zip 檔案
進行解壓後,使用瀏覽器擴充套件程式載入已解壓的檔案進行擴充套件
新增外掛

繪製折線圖

import matplotlib.pyplot as plt
plt.plot(x 列表資料, y 列表資料)
除了可以是列表資料之外
還可以是 pandas 庫的 <class 'pandas.core.series.Series'>  型別

不可以是 字典.keys() 和 字典.values() 型別

繪製散點圖

plt.scatter(x, y)

x ,可以為列表型別,字典的鍵值 keys(),values() 型別
range物件及 Series型別

y 可以為列表型別,字典的鍵值 keys(),values() 型別
Series 型別

可以新增 顏色 和 標籤

plt.scatter(x,y,color="g",label="標籤")

使用 plt.legend() 顯示圖例

繪製柱狀圖

plt.bar(x,y)

x 可以為 字典的鍵值對型別,列表型別,可以為 Series 資料型別

y可以為 字典的鍵值對型別,列表型別,可以為 Series 資料型別

繪製餅圖

plt.pie(
    值,
    labels= 名稱,
    # 標籤名稱
    shadow=True,
    # 陰影
    autopct='%1.1f%%'
    # 顯示 百分比
)

值 可以是字典的鍵值對型別 .keys(),可以是列表型別,

名稱 可以是字典的鍵值對型別 .values(),可以是列表型別,

繪製詞雲圖

name = ''
# 名稱
lst = list(df['列名'])
# 列名對應的元素的集合
for i in range(len(df)):
    name += lst[i]
ls = jieba.lcut(name)
txt = " ".join(ls)
w = wordcloud.WordCloud(font_path=r'C:\Windows\Fonts\STXINWEI.TTF',
                        width = 1000,height = 700,background_color = "white",
                       )

w.generate(txt)
w.to_file("詞雲圖.png")
繪製盒圖
使用 sns.boxplot(data = data) 進行繪製

import seaborn as sns
import numpy as np 

sns.set_style("whitegrid")
data = np.random.normal(size=(20, 6)) + np.arange(6) / 2

sns.boxplot(data=data)
繪製小提琴圖


sns.violinplot(data)


data 為 np.random.normal(size=(20, 6)) + np.arange(6) / 2

此處的 data 為 <class 'numpy.ndarray'> 資料型別
補充 :
折線圖的繪製


plt.plot([0, 1], [0, 1], sns.xkcd_rgb["pale red"], lw=3)
plt.plot([0, 1], [0, 2], sns.xkcd_rgb["medium green"], lw=3)
plt.plot([0, 1], [0, 3], sns.xkcd_rgb["denim blue"], lw=3)

使用 sns.xkcd_rgb 進行選擇線條的顏色

繪製地形圖

x, y = np.random.multivariate_normal([0, 0], [[1, -.5], [-.5, 1]], size=300).T
pal = sns.dark_palette("green", as_cmap=True)
sns.kdeplot(x, y, cmap=pal);

補充 
繪製柱狀圖

x = np.random.normal(size=100)
sns.distplot(x,kde=False)


x = np.random.gamma(6, size=200)
sns.distplot(x, kde=False, fit=stats.gamma)


x = np.random.gamma(6, size=200)
sns.distplot(x, kde=False, fit=stats.gamma)

補充 
繪製散點圖
使用 sns.joinplot(x = '名稱',y = '名稱',data = 資料)

mean, cov = [0, 1], [(1, .5), (.5, 1)]

data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x", "y"])


sns.jointplot(x="x", y="y", data=df)

散點圖擴充套件:


sns.stripplot(x="day", y="total_bill", data=tips, jitter=True)


sns.swarmplot(x="day", y="total_bill", data=tips)


sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips)


sns.swarmplot(x="total_bill", y="day", hue="time", data=tips)

繪製 點圖

sns.pointplot(x="sex", y="survived", hue="class", data=titanic)


sns.pointplot(x="class", y="survived", hue="sex", data=titanic,
              palette={"male": "g", "female": "m"},
              markers=["^", "o"], linestyles=["-", "--"]);
多層面板分類圖
tips = sns.load_dataset("tips")


sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips)


factorplot(x="day", y="total_bill", hue="smoker", data=tips, kind="bar")


sns.factorplot(x="day", y="total_bill", hue="smoker",
               col="time", data=tips, kind="swarm")



sns.factorplot(x="time", y="total_bill", hue="smoker",
               col="day", data=tips, kind="box", size=4, aspect=.5)
繪製熱力圖
sns.heatmap(資料)

uniform_data = np.random.rand(3, 3)
heatmap = sns.heatmap(uniform_data)

可以新增的屬性為

vmin=0.2, vmax=0.5

center=0,linewidths=.5

annot=True,fmt="d"

cbar=False,cmap="YlGnBu"

今日成果:爬取百度貼吧
'''
第一頁
https://tieba.baidu.com/f?kw=python&ie=utf-8&pn=0
# 第二頁
https://tieba.baidu.com/f?kw=python&ie=utf-8&pn=50
# 第三頁
https://tieba.baidu.com/f?kw=python&ie=utf-8&pn=100
'''

from urllib.parse import urlencode
# 匯入解析模組
from urllib.request import Request,urlopen
# Request 請求 , urlopen 開啟
def get_html(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
    }
    request = Request(url,headers=headers)
    response = urlopen(request)
    # print(response.read().decode("gbk","ignore"))
    # 返回的是二進位制資料
    return response.read()

def save_html(filename,html_bytes):
    with open(filename,'wb') as f:
        # 使用 wb 進行儲存資料
        f.write(html_bytes)

def main():
    base_url = 'https://tieba.baidu.com/f?ie=utf-8&{}'
    # 貼吧 url
    content = input("請輸入要進行查詢的內容:")
    # 要進行查詢的內容
    num = int(input("請輸入要下載的頁數:"))
    for pn in range(num):
        print("正在下載第{}頁".format(pn + 1))
        args = {
            'kw':content,
            # 內容
            'pn':pn * 50
            # 頁碼
        }
        args = urlencode(args)
        # 進行轉碼
        html_bytes = get_html(base_url.format(args))
        # 傳遞拼接後的 base_url 給 get_html 函式
        filename = "" + str(pn+1) + "頁.html"
        # 下載到本地的檔名稱
        save_html(filename,html_bytes)

if __name__ == '__main__':
    main()

urlopen方法


#coding=gbk
from urllib.request import urlopen
# urlopen 開啟網頁使用
url = 'https://www.baidu.com/'
# 要進行訪問的 URL
response = urlopen(url)
# 傳送請求
print(response.getcode())
# 獲取 HTTP 響應碼  200
print(response.geturl())
# 獲取訪問的網址資訊 https://www.baidu.com/
print(response.info())
# 獲取伺服器響應的HTTP請求頭
info = response.read()
# 讀取內容
print(info.decode())
# 列印內容

Request 方法


request = Request(url = url,headers = headers)
# 帶著 ua 去請求資訊
print(request.get_header("User-agent"))
# 獲取請求頭資訊
response = urlopen(request)
info = response.read()

安裝 fake_useragent 第三方庫
檢視 headers 資訊

from fake_useragent import UserAgent
ua = UserAgent()
print(ua.chrome)
# 列印谷歌瀏覽器
# print(dir(ua))
print(ua.ie)
# 列印 IE 瀏覽器
print(ua.firefox)
# 列印火狐瀏覽器

使用 get 請求


from urllib.request import urlopen,Request
from urllib.parse import quote
# urlopen 開啟網頁使用
# Request 請求物件,帶有 ua
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
}
url = 'https://www.baidu.com/s?wd={}'.format(quote('瀚陽的小驛站'))
# 要進行訪問的 URL , 使用 quote 進行轉碼
# 使用 urllib.parse 中的 urlencode 和 quote 方法 進行轉碼
# quote('瀚陽的小驛站') 進行轉碼 '%E7%80%9A%E9%98%B3%E7%9A%84%E5%B0%8F%E9%A9%BF%E7%AB%99'
request = Request(url,headers = headers)
# 進行請求
response = urlopen(request)
print(response.read().decode())

from urllib.request import urlopen,Request
from urllib.parse import urlencode
from fake_useragent import UserAgent
# urlopen 開啟網頁使用
# Request 請求物件,帶有 ua
# 使用 urlencode 對字典元素進行轉換編碼
args = {
    'wd':"瀚陽的小驛站",
    "ie":"utf-8"
}

headers = {
'User-Agent': UserAgent().random
}

url = 'https://www.baidu.com/s?wd={}'.format(urlencode(args))

print(url)
request = Request(url , headers = headers)
response = urlopen(request)
info = response.read()
print(info.decode())

map,reduce,filter基礎實現
#coding=gbk
from operator import add
# 匯入加法
# map 函式名 , 序列物件
print(list(map(str,range(5))))
print(list(map(len,['abc','1234'])))
# [3, 4]
for num in map(add,range(3),range(1,4)):
    # 對 0+1 , 1+2 , 2+3
    print(num)

from functools import reduce
from operator import add,mul,or_
seq = range(1,10)
# 1~9 的所有元素
print(reduce(add,seq))
# 連加,seq 中的每一個元素
print(reduce(mul,seq))
# 連乘,seq 中的每一個元素
seq = [{1},{2},{3},{4},{5}]
print(reduce(or_,seq))
# 將 seq 中的元素並集在一起,or_

seq = ['abcd','1234',',.?!','']
print(list(filter(str.isdigit,seq)))
# 只保留元素全是數字的
print(list(filter(str.isalpha,seq)))
# 只保留元素全是字母的
print(list(filter(None,seq)))
# 保留等價於 True 的元素
gen = (2 ** i for i in range(5))
for i in gen:
    print(i,end = ' ')
print()

x,y,z = map(int,'123')
print(x,y,z)

資料分析小題

DataFrame物件是一個表格型的資料結構 
DataFrame物件的列是有序的 
DataFrame物件列與列之間的資料型別可以互不相同 

檔案寫操作時,writelines方法的引數可以是列表 元組 字典 

wordcloud.WordCloud()函式中的引數mask是用來設定 詞雲的遮罩形狀 

pandas提供了對各種格式資料檔案的讀取和寫入工具,其中包括
CSV檔案 文字檔案 工作簿檔案 

requests庫的get()函式執行後會返回一個Response型別的物件,其text屬性以 字串 形式儲存響應內容。

在matplotlib子圖繪製中,若執行plt.subplot(3,2,4),則當前的繪圖子區域索引號是 4

建立3*3單位矩陣 A=np.eye(3) 

jieba.cut(s)函式分詞功能 精確模式分詞 

data1=np.loadtxt('data_txt.txt')
將文字檔案“data_txt.txt”讀取到陣列data1中

matpltlib中繪製圖形,通過更改繪圖框的尺寸來設定相等的縮放比例的引數 
scale

import numpy as np
Array1 = np.linspace(1,5,3,dtype=int)
print(Array1)

[1 3 5] 

在python中,獲取當前工作目錄可以通過 os 庫的getcwd函式獲取

如果想返回DataFrame的所有列的平均值,可以使用 mean 統計函式

numpy的ndarray中的維度稱為 軸

pandas中實現表格型資料集的物件是 DataFrame

試圖將句子最精確地切開,適合文字分析的分詞模式叫做 精確 模式分詞

使用transpose函式可以實現numpy陣列按軸進行轉置

s=pd.Series([1,2,3,4]),則np.sqrt(s)是對s中的每一個數值求平方根

CSV檔案本質上也是文字檔案,可以用記事本或者excel開啟。

帶有else子句的異常處理結構,如果不發生異常則執行else子句中的程式碼

wordcloud.WordCloud()函式中的引數max_words 設定要顯示的詞的最大個數

 求最大公約數最小公倍數

#coding=gbk
import math
m = int(input())
n = int(input())

print(math.gcd(m,n))
# 最大公約數
print((m*n)//math.gcd(m,n))
# 最小公倍數


 
將字串 s="alex" 轉換成列表 list(s)

不能使用 del 刪除集合中的部分元素

組合資料型別的分類

序列型別、集合型別、對映型別


簡述列表在實現基本資料同時發揮的重要作用


1)列表是一個動態長度的資料結構,可以根據需求增加或減少元素。
2)列表的一系列方法或操作符為計算提供了簡單的元素運算手段。
3)列表提供了對每個元素的簡單訪問方式及所有元素的遍歷方式


請列出5條寫出優美程式碼的程式設計原則


(1) 清晰明瞭,規範統一; 
(2) 邏輯簡潔,避免複雜邏輯; 
(3) 介面關係要清晰; 
(4) 函式功能扁平,避免太多層次巢狀; 
(5) 間隔要適當,每行程式碼解決適度問題

 matplotlib 去掉座標軸


#去掉x軸
plt.xticks([])  


#去掉y軸
plt.yticks([])  


#去掉座標軸
plt.axis('off')  

關於這學期的總結
# 例1-2  正確縮排
# 比較兩個數字對於π的精度,保持縮排一致
pie = 3.1415
pie1 = 3.14
# 同一程式碼塊內各行縮排空格數目相同,觀察輸出結果
if pie > pie1:
    print('π取pie更精確')
elif pie == pie1:
    print('π取pie或pie1一樣精確')
else:
    print('π取pie1更精確')

# 例1-4  長語句換行
# 給出3種水果的價格,計算總價
apple_price, banana_price, pear_price = 1, 1.5, 0.5
# 通過反斜槓實現長語句換行
total_price = apple_price + \
banana_price + \
pear_price
print('total_price =', total_price)

# 例1-5  逗號換行
# 方括號內,在逗號後直接換行
total_price = sum([apple_price, 
            banana_price, 
            pear_price])
print('total_price =', total_price)

# 例1-6  分號隔離
# 給出3種水果的價格,計算總價
apple_price = 1; banana_price = 1.5; pear_price = 0.5
total_price = apple_price + banana_price + pear_price
print('total_price =', total_price)

import   keyword
print('Python中的所有保留字為:\n',keyword.kwlist)

# 例1-8   賦值的基本形式
# 使用等號直接給num_int賦值一個整數值
num_int = 1
print('使用等號建立的整數為:', num_int)

# 使用等號直接給num_float賦值一個浮點數值
num_float = 9.9
print('使用等號建立的浮點數為:', num_float)

# 使用等號直接給string賦值一個字串
string = 'python'
print('使用等號建立的字串為:', string)

# 例1-9  序列賦值
# 序列賦值可給變數賦值多種資料型別
num_int, string, list1 = 123, 'str', [4,6]
print('賦值建立的多種資料型別為:', num_int, string, list1)
# 序列賦值可給變數賦值已賦值的變數
num1, num2, num3 = 7, 8, 9
num_int1, num_int2, num_int3 = num1, num2, num3
print('變數賦值為已賦值變數結果為:', num_int1, num_int2, num_int3)

# 例1-10  連結賦值
str1 = str2 = str3 = 'STR'
print('str1, str2, str3分別為:', str1, str2, str3)

print('str1, str2, str3的記憶體地址分別為:', id(str1), id(str2), id(str3))

print('str1, str2, str3是否等價:', str1 is str2 is str)

# 程式碼1-11  增量賦值
x = 100
x += 10
print('x += 10等價於x=x+10,其值為:', x)

# 例1-12  算術運算
num_int = 4
num_float = 4.0
print('整數與浮點數的和為:', num_int + num_float)
print('整數與浮點數的差為:', num_int - num_float)
print('整數與浮點數的積為:', num_int * num_float)
print('浮點數與整數的商為:', num_float / num_int)
print('浮點數對整數取模結果為:', num_float % num_int)
print('浮點數的整數次冪為:', num_float ** num_int)

# 例1-13  賦值運算
num_int1 = 4
print('賦值後num_int1為:', num_int1)
num_int1 = 4 + 6
print('賦值後num_int1為:', num_int1)
num_int1 = 4 * 2
print('賦值後num_int1為:', num_int1)
num_int1 = 4 / 2
print('賦值後num_int1為:', num_int1)
num_int1 = 4 % 2
print('賦值後num_int1為:', num_int1)
num_int1 = 4 ** 2
print('賦值後num_int1為:', num_int1)

# 例1-14  比較運算
num_int = 4
num_float = 4.0
print('num_int與num_float是否相等:', num_int == num_float)
print('num_int與num_float是否不相等:', num_int != num_float)
print('num_int是否大於num_float:', num_int > num_float)
print('num_int是否小於num_float:', num_int < num_float)
print('num_int是否大於等於numfloat:', num_int >= num_float)
print('num_int是否小於等於num_float:', num_int <= num_float)


# 例1-15  邏輯運算
num_bool1 = False
num_bool2 = True
print('num_bool1 and num_bool2返回值為:', num_bool1 and num_bool2)

print('num_bool1 or num_bool2返回值為:', num_bool1 or num_bool2)

print('not num_bool2的返回值為:', not (num_bool2))

# 例1-16 身份運算
num_int1 = 15
num_int3 = 15
print('num_int1與num_int3儲存單位是否相同:', num_int1 is num_int3)

num_int2 = 15.0
print('num_int1與num_int2儲存單位是否相同:', num_int1 is num_int2)

# 如果儲存單位相同就返回True,否則返回False
print('num_int1與num_int3儲存單位是否不同:', num_int1 is not num_int3)

print('num_int1與num_int2儲存單位是否不同:', num_int1 is not num_int2)

# 例1-17 成員運算
num_int1 = 15
list2 = [1, 'apple', 15]
print('num_int1是否在list2中:', num_int1 in list2)

array = ('orange', 6, 15)
print('num_int1是否不在array中:', num_int1 not in array)


# 例1-18 運算子優先順序
# 先執行乘除法運算,再執行加減法運算
print('num_float + num_int1 / num_int3 =', num_float + num_int1 / num_int3)
# 先執行加減法運算,再執行比較運算
print('num_int1 - num_int2 > num_int1 - num_int3:',
      num_int1 - num_int2 > num_int1 - num_int3)
# 先執行加減法運算,再做身份判斷
print('num_int1 - num_int3 + num_int1 is num_int1:',
      num_int1 - num_int3 + num_int1 is num_int1)
# 先執行指數運算,再執行減法運算,最後做身份判斷
print('num_float ** 2 - 1 is not num_int2:',
      num_float ** 2 - 1 is not num_int2)

#例1-19 建立 number
num_int = 2
num_float = 4.5
num_bool = True
num_complex = 3j
print('資料型別分別為:\n', type(num_int),
      type(num_float), type(num_bool), type(num_complex))

# 例1-20 number 型別裝換與混合運算
# number型別轉換, 將float轉換為int(直接去掉小數部分)
print('int(4.5)的結果為:', int(4.5))
# 將int轉換為float(直接增加小數部分)
print('float(4)的結果為:', float(4))
# 將int和float轉換為complex(直接增加虛部)
print('complex(4)和complex(4.5)的結果分別為:', complex(4), complex(4.5))
# 不同number型別混合運算, int + float = float
print('整數和浮點數和的型別為:', type(124 + 4.0))
# int + complex = complex
print('整數和複數和的型別為:', type(124 + 5.3j))
# float + complex = complex
print('浮點數和複數和的型別為:', type(4.0 + 5.3j))

# 例1-21 str 索引
string = "ilovePython"
# 下標為正數,從第2個字元開始索引,到第5個字元
print('ilovePython[1:5] =', string[1:5])
# 下標為負數,從倒數第10個字元開始索引,到倒數第6個字元
print('ilovePython[-10:-6] =', string[-10:-6])
print('ilovePython[:5] =', string[:5])
 # 尾下標留空,從第2個字元開始索引,到最後一個字元截止
print('ilovePython[1:] =', string[1:])
# 按步索引,從第2個元素開始索引,到第11個元素,步距為3
print('ilovePython[1:10:3] =', string[1:10:3])

# 例1-22 str 查詢方法
print('string中n的位置和總數分別為:', string.index('n'), string.count('n'))
print('string中是否只包含字母:', string.isalpha())
print('string中是否只包含數字:', string.isdigit())
print('string是否已P開頭:', string.startswith('P'))
print('string是否是標題化的:', string.istitle())

# 例1-23 str 改寫方法
print('string左對齊填充至20個字元結果為:', string.ljust(20))
print('string右對齊填充至20個字元結果為:', string.rjust(20))
print('string大寫化結果為:', string.upper())
print('string大小寫置換結果為:', string.swapcase())
print('string中h替換為H結果為:', string.replace('h','H'))

# 例1-24 str 方法-其他
# 以指定格式編碼
string = string.encode('UTF-16', 'strict')
print ("string編碼為:", string)
# 以指定格式解碼
string = string.decode('UTF-16', 'strict')
print ("string解碼為:", string)
# 以指定分隔符分割str
print(string.partition("."))
string1 = ('I','love','Python')
sep = '-'
# 以sep為分隔將string1合併為新的字串
print('以sep分隔合併string1為:', sep.join(string1))

# 例1-25 str 轉義與常用操作
print ('\note\mybook')  # str中包含\n,識別為換行符並轉義

print ('\title\mybook')  # str中包含\t,識別為製表符並轉義

print (r'\note\mybook ')  # 使用r制止轉義

print (string + "TEST")  # 輸出連線的str

print (string * 2)  # 輸出str兩次

# 例1-26 建立 list
# 使用方括號建立一個非空list
list1 = ['runoob', 786, 2.23, 'john']
print('方括號建立的列表為:', list1)
#建立元組
tuple1 = (123, 'xyz', 'zara', 'abc')
list2 = list(tuple1)
print('元組轉換成列表結果為:', list2)

# list函式將str拆開,作為新list中的元素
list3 = list('china')
print('字串轉換成列表結果為:', list3)

# 例1-27 list 基本操作
print('列表按指定長度索引結果為:', list3[-4:-2])

print('列表按步長索引結果為:', list3[0::2])

list1[2] = 666
print('列表替換結果為:', list1)

print('list1和list2用+連線結果為:', list1 + list2)

print('列表通過*重複結果為:', list1 * 2)

# 例1-28 list 常用方法
print('list3中a出現的次數:', list3.count('a'), '\n',   'list3中a首次出現的位置:', list3.index('a'))
list3.insert(0,'g')
list1.append('新增')
list2.extend(list3)
print('在列表指定位置插入元素:', list3, '\n',      '在列表末尾新增元素:', list1, '\n',      '將list3擴充套件至list2:', list2)
list3.insert(0,'g')
list1.append('新增')
list2.extend(list3)
print('在列表指定位置插入元素:', list3, '\n',      '在列表末尾新增元素:', list1, '\n',      '將list3擴充套件至list2:', list2)

list3.pop(0)
list1.remove('新增')
print('使用pop刪除指定位置的元素:', list3, '\n',      '使用remove刪除指定元素:', list1)
list2.pop(0)
list2.sort()
list3.reverse()
print('列表排序:', list2, '\n',      '列表反向排序:', list3)

# 例1-29 建立tuple
# 使用圓括號建立tuple
tup1 = ('Google', 'Runoob')
print('檢視tup1型別:', type(tup1), '\n',      '檢視tup1:', tup1)
# 不加括號建立tuple
tup2 = "a", "b", "c", "d"
print('檢視tup2:', tup2, '\n',      '檢視tup2型別:', type(tup2))

# 將[‘x',’y',’z']轉換成tuple
tup3 = tuple(['x','y','z'])
print('檢視tup3:', tup3, '\n',      '檢視tup3型別:', type(tup3))
# 單個數字元素加逗號,變數是tuple
tup4 = (50,) 
# 單個數字元素無逗號,變數是int
tup5 = (50)
print('tup4和tup5的型別分別為:', type(tup4), type(tup5))

# 例1-30 tuple 基本操作
print('tup2中第3元素為:', tup2[2])
print('tup2中第1個到倒數第二個元素為:', tup2[:-1])

print('連線兩個元組結果為:', tup1 + tup2)

print('元組重複輸出結果為:', tup3 * 2)

# 例1-31 tuple 內建方法
print('tup2中元素a出現的次數:', tup2.count('a'))

print('tup2中元素a首次出現的位置:', tup2.index('a'))

# 例1-32 建立 dict
# 使用花括號建立空dict,更新鍵值對
dict1 = {}
dict1['one'] = "This is 1"
dict1['two'] = "This is 2"
print('檢視字典:', dict1)
# 使用dict函式建立dict,指定鍵值對
dict2 = dict(name='小明', height=187)
print('檢視字典:', dict2)

# 例1-33
print('通過鍵索引字典元素:', dict1['one'])

dict1['one'] = 'this is 1'
print('以鍵改字典元素值:', dict1)

dict1[3] = 'This is 3'
print('更新後的字典為:', dict1)

del dict1[3]
print('刪除鍵3後的字典為:', dict1)

# 例1-34 dict 內建方法
print('輸出dict1中所有鍵值對:', dict1.items(), '\n',
      '輸出dict1中所有的鍵:', dict1.keys(), '\n',
      '輸出dict1中所有的值:', dict1.values())

print('與one對應的元素為:', dict1.get('one'), dict1.setdefault('one'))

dict1.update(dict2)
dict3 = dict2.copy()
print('將dict2中鍵值對更新到dict1中:', dict1, '\n',
      '將dict2中內容複製到新的字典中:', dict3)

dict1.pop('name')
dict2.popitem()
dict3.clear()
print('刪除dict1中name鍵對應的內容:', dict1, '\n',
      '隨機刪除dict2中的一個鍵值對為:', dict2.popitem(), '\n',
      '清空dict3中的內容:', dict3)

# 例1-35 建立 set
# 使用非空的{}建立set
set1 = {1, 2, 3}
print('set1的型別為:', type(set1))
# 建立一個空的set只能使用set函式
set2 = set()
print('檢視set2:', set2, '\n',   'set2的型別為:', type(set2))
# 將list、tuple轉換為set
set3 = set([1,2,3])
set4 = set((1,2,3))
print('檢視set3和set4:', set3, set4, '\n',
      'set3和set4的型別分別為:', type(set3), type(set4))

# 例1-36 set 常用方法
set1.add('a')
print('add方法向set1中新增元素結果為:', set1)

set1.pop()
print('pop方法刪除set1中任意一個元素結果為:', set1)

set2.clear()
print('清除set2中內容結果為:', set2)

# 例1-37 set 集合運算
print('set4是否為set1的子集:', set4 < set1)

print('set4和set1的並集為:', set4 | set1)

print('set4和set1的交集為:', set4 & set1)

print('set4和set1的差集為:', set4 - set1)

# # 例1-38 輸入不同資料型別
# # 輸入一個數字,由Python預設型別
# number1 = input('請輸入一個數字:')

# # 輸入一個str,由Python預設型別
# str1 = input('請輸入一個字串:')

# # 輸入一個數字,並將其轉換為int型別
# number2 = int(input('請輸入一個數字:'))

# # 檢視以上輸入的輸出結果型別
# print('number1、str1和number2的型別分別為:\n',
#       type(number1), type(str1), type(number2))


# 例1-39 print 函式應用
# print函式接受多個str
print('我', '愛', '中華')

# print函式在列印前計算結果
print('100+200 =', 100 + 200)

# 例1-40 “ % + 格式符” 格式化輸出
# 用%s、%d分別格式化字串'Zara'和整數20
print("我的名字叫做%s,已經%d歲了!"%('Zara',20))

# 用%d格式化16,用%o將十進位制整數16用八進位制數表示
print("%d 的八進位制是 %o"%(16,16))

# 用%.3f將整數轉化為保留小數點後3位的float
print("23 轉化為保留3位小數的浮點數%.3f"%(23))

# format函式不帶引數情況下的輸出
print("我的名字叫做{},已經{}歲了!".format('Zara', 18))

# format函式帶數字編號並打亂順序
print("我的名字叫做{1},已經{0}歲了!".format(18, 'Zara'))

# format函式帶關鍵字引數
print("我的名字叫做{name},已經{age}歲了!".format(age=18,name='Zara'))

# format函式格式化數字為二進位制數
print("我的名字叫做{},已經{:b}歲了!".format('Zara', 18))

# # 例1-41 read 函式讀取 test.txt 檔案
# # 以只讀模式開啟test.txt檔案
# data = open('../data/test.txt', 'r')
# # 讀取檔案中的內容,存到content變數中
# content = data.read()
# # 打印出content變數中包含的文字內容
# print('該文字中的內容是:', content)

# #例1-42 write 函式寫入檔案
# # 開啟一個檔案
# web = open('../data/web.txt', 'w')
# # 轉換內容,寫入檔案
# value = ('http://www.tipdm.org', 14)
# str_value = str(value)
# web.write(str_value)
# web.close()
# # 開啟文字,讀取出寫入的內容
# web = open(‘../data/web.txt', 'r')
# content = web.read()
# print('該文字中的內容是:', content)

# # 例1-43 if-else語句實現登入介面
# name = input ('請輸入使用者名稱:')
# password = input ('請輸入密碼:')
# if name == "Lucy" and password == "123456":
#     print ('****登入成功,歡迎!*****')
# else:
#     print ('-----您的輸入有誤,登入失敗!-----')

# # 例1-44 使用if-elif-else語句實現年齡段的判斷
# age = input('請輸入您的年齡:')
# age = int(age)
# if age < 18:
#     print('未成年人!')
# elif age >= 18 and age <= 25:
#     print('青年人!')
# elif age > 25 and age <= 60:
#     print('中年人!')
# else:
#     print('老年人!')


# #例1-45 巢狀if-elif-else語句
# age = input('請輸入你的年齡:')
# age = int(age)
# if age == 35:
#     nation = input('請輸入你的國籍:')
#     if nation == '英國':
#         print('你是Tom! ')
#     elif (nation == '法國'):
#         print('你是Frank! ')
#     else:
#         print('你是Bob! ')
# elif age == 21:
#    print('你是Jane,來自南非! ')
# elif age == 51:
#    print('你是Washington,來自澳大利亞! ')
# else:
#    print('請輸入正確年齡值! ')

# 例1-46  if-else語句的單行形式
num1, num2 = 11, 90
print('num1加num2為百分數') if 1000 > num1 + num2 >100 else print('num1加num2不為百分數')

# 例1-47 for語句遍歷提取str
# 單純遍歷的for語句
names = ['Michael', 'Bob', 'Tracy']
# 遍歷輸出names中的元素
for name in names:
    print(name)

#例1-48 for語句遍歷查詢dict
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 遍歷鍵值對
print('\nkey_value:', end = '')
for key, value in dic.items():
    print(key, value, sep = ':', end = ' ')
# 遍歷鍵
print('\nkeys:', end = '')
for key in dic.keys():
    print(key, end = ' ')
# 遍歷值
print('\nvalues:', end = '')
for value in dic.values():
    print(value, end = ' ')

# # 例1-49 巢狀for語句
# students = ['小明', '小紅']
# subjects = ['語文', '數學'] 
# sum1 = []
# avg = []
# for i in students: 
#     print ('開始錄入%s的考試成績!'%i) 
#     sum = 0
#     for j in subjects: 
#         print('請輸入%s成績:'%j) 
#         score = int(input())
#         sum += score
#     average = sum / 2
#     avg.append(average)
#     sum1.append(sum)
# print(students, '的總分依次是', sum1, ',', '平均分依次是', avg)
# print('完成成績錄入!')

# 例1-50 while語句
sum = 0
n = 99
while n > 0:
    sum += n
    n -= 2
print(sum)

# # 例1-51 巢狀while語句
# j = 1
# while j <= 2:
#     sum = 0
#     i = 1
#     name = input('請輸入學生姓名:')
#     while i <= 2:
#         print ('請輸入第%d門的考試成績: '%i)
#         sum += int(input())
#         i += 1
#     avg = sum / (i-1)
#     print(name, '的平均成績是%d'%avg)
#     j += 1
# print('學生成績輸入完成!')


# 例1-52 break語句的使用
# break語句用於for迴圈
string = "Python"
for i in string:
# 遍歷至string中的字元n時,不再執行else程式碼塊
    if i == 'n':
        break
    else:
        print("letter:{}". format(i))

# break語句用於while迴圈
counts = 0
while True:
    print(counts)
    counts += 1
# 滿足counts等於3時跳出迴圈,不再進入迴圈體
    if counts == 3: 
        break

# 例1-53
# 第一層迴圈,遍歷次數為2
for i in range(2):
    print("-----%d-----" %i)
# 第二層迴圈,遍歷次數為5
    for j in range(5):
# 當j等於2或4時,不執行迴圈體
        if j == 2 or j == 4:
            continue
        print(j)

# 例1-54
for element in "Python":
# element為y時,不做任何操作,不會被輸出
    if element == "y":
        pass
    else:
        print(element)        

counts = 0
while counts < 5:
    counts += 1
# i=3時,不執行迴圈體
    if counts == 3:
        pass
    else:
        print(counts ** 2)

# 例1-55 
vec = [-4, -2, 0, 2, 4]
# 用vec中元素的倍數,建立一個數組
print([x * 2 for x in vec])

# 建立一個包含2元tuple的list
print([(x, x ** 2) for x in range(6)])


# 例1-56
list1 = [1, 2, 3, 4]
# bytes函式、bytearray函式
print('list1的不可變位元組陣列為:', bytes(list1), '\n',
      'list1的可變位元組陣列為:', bytearray(list1))

# chr函式、ord函式
print('整數40的unicode字元為:', chr(40), '\n',
      'unicode字元(對應的整數為:', ord('('))

# bin函式
print('整數40的二進位制形式為:', bin(40))

# ascii函式
print('字串tipdm的ascii碼為:', ascii('tipdm'))

# hash函式
print('字串tipdm的hash值為:', hash('tipdm'))

# 例 1-57
# max函式、min函式
print('序列中的最大數為:', max(list1), '\n',
      '序列中的最小數為:', min(list1))
# abs函式
print('-10和100的絕對值分別為:', abs(-10), abs(100))

# pow函式
print('3的6次方為:', pow(3, 6))

# round函式
print('3.2四捨五入結果為:', round(3.2))

# divmod函式
print('7除以3的商和餘數分別為:', divmod(7, 3))
#例 1-58
# map函式
# 對一個list中的各個float分別四捨五入
print('浮點數的四捨五入結果為:', list(map(round, [1.1, 2.2, 3.3, 4.4, 5.5])))
# zip函式
list3 = [1, 2, 3]
list4 = [4, 5, 6]
zipped = zip(list3, list4)
# zip函式直接返回的是資料物件
print('返回物件為:', zipped, '\n',  '返回為list:', list(zipped))

# 例1-59
def exponent(a, b):
    x = a ** b
    return x
print('自定義冪運算的返回值為:', exponent(3, 6))

# 例 1-60
# 無引數,無返回值
def  hello():
    print('Hello!')
hello()
print('***以上為hello()的輸出,以下為print(hello())的輸出***')
print(hello())

# 無引數,有返回值
def func():
    return("Python")
func()

# 多引數,無返回值
def func1(a, b):
    print("a + b = %d"%(a + b))
func1(3, 4)

# 多引數,有返回值
def func2(a, b):
    return (a + b)
print('a、b加和為:', func2(4, 3))


# 多個返回值
def maxtomin(a, b):
#返回a,b從大到小的排列
    if a > b:
        return  a, b
    else:
        return  b, a
print('a、b排序為:', maxtomin(2, 4))

# 例 1-61
# 使用位置引數
def  func3(b, a, c):
    return (a ** 2, b ** 2, c ** 2)
result = func3(1, 2, 3)
print('1、2、3經函式func3運算的結果為:', result)

# 使用關鍵字引數
def  func4(a, b, c):
    return (a ** 2, b ** 2, c ** 2)
result1 = func4(b=2, a=1, c=3)
print('1、2、3經函式func4運算的結果為:', result1)

# 混合使用位置引數和關鍵字引數,位置引數必須在關鍵字引數的前面
def  func5(a, b, c):
    return (a ** 2, b ** 2, c ** 2)
result2 = func5(1, c=3, b=2)
print('1、2、3經函式func5運算的結果為:', result2)

# 例1-62
def  func6(a, b = 2):
    print(a, b)
func6(1)
def  func7(string, *numbers):
    print(string, numbers)
func7('numbers:', 1, 2, 3)
def  func8(a, *numbers, **kwargs):
    print (a, numbers, kwargs)
func8(4, 2, 3, 4, b = 2, c = 3)

# 例1-63
x = 99
def func9(y):
    return x + y
print('y = 1, x + y為:', func9(1))

def func10(y):
    x = 12 
    return x + y
print('x為:', x, '\n',
      'y=1, x+y為:', func10(1))

# 例1-64
x, y, z = 0, 2, 3
def func11():
    x = 1
print('x + y與z是否相等:', x + y == z)

# 呼叫函式
func11()
print('x + y與z是否相等:', x + y == z)

def func12():
    global x
    x = 1

print('x + y與z是否相等:', x + y == z)

# 呼叫函式
func12()
print('x + y與z是否相等:', x + y == z)

# 例1-65
x = 1
list1 = [1, 2]
def func13(x,y):
    x = 2
    y[0] = 'str'
func13(x, list1)
print('呼叫函式後傳入的引數變化為:', x, list1)

# 例1-66
sum1 = lambda arg1, arg2: arg1 + arg2
print("相加值為:", sum1(10, 20))
# 使用lambda語句
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
f1 = lambda x: '傳入的引數為1' if x == 1 else '傳入的引數不為1'
f1(10)

# #1. 輸入一個包含若干自然數的列表,輸出這些數的平均值,結果保留3位小數。
# data=eval(input('請輸入一個包含若干自然數的列表:'))
# avg=sum(data)/len(data)
# avg=round(avg,3)
# print('平均值為:',avg)

# #2. 輸入一個包含若干自然數的列表,輸出一個新列表,新列表中每個元素為原列表中每個自然數的位數。
# data=eval(input('請輸入一個包含若干自然數的列表:'))
# data=map(str,data)
# length=list(map(len,data))
# print('每個元素的位數:',length)

# #3. 輸入一個字串,輸出其中每個唯一字元最後一次出現的下標。
# text=input('請輸入一個字串:')
# positions=[(ch,index) for index,ch in enumerate(text) if (index==text.rindex(ch)) and (text.count(ch)==1)]
# print(positions)

# #4. 輸入一個字串,檢查該字串是否為迴文,輸出yes / no,要求用切片實現。
# text=input('請輸入一個字串:')
# if text==text[::-1]:
#     print('yes')
# else:
#     print('no') 


# #5. 接收兩個正整數引數n和a(要求a為小於10的自然數),計算形如a+aa+aaa+…+aaa...aaa的表示式前n項的值。
# def compute(n,a):
#     return(sum(map(lambda i:int(str(a)*i),range(1,n+1))))
# print(compute(3,5))


# 例3-1
import numpy as np
print('整數42轉換為浮點數結果為:', np.float64(42)) 
print('浮點數42.0轉換為整數結果為:', np.int8(42.0)) 
print('浮點數42轉換為布林型轉換結果為:', np.bool(42.0))
print('整數0轉換為布林型結果為:', np.bool(0))
print('布林型資料True轉換為浮點數結果為:', np.float(True))
print('布林型資料False轉換為整型結果為:', np.int8(False))

#例3-2
arr1 = np.array([1, 2, 3, 4])
print('建立的一維ndarray為:', arr1)
arr2 = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]])
print('建立的二維ndarray為:\n', arr2)    
print('ndarray arr2的維數為:', arr2.ndim)
print('ndarray arr2的形狀為:', arr2.shape)
print('ndarray arr2的資料型別為:', arr2.dtype)
print('ndarray arr2的元素個數為:', arr2.size)
print('ndarray arr2每個元素的大小為:', arr2.itemsize)


# 程式碼 3-3
print('使用arange函式建立的ndarray為:', np.arange(0, 1, 0.1))
print('使用linspace函式建立的ndarray為:\n',np.linspace(0, 1, 12))
print('使用logspace函式建立的ndarray為:\n', np.logspace(0, 2, 20))
print('使用zeros函式建立的ndarray為:\n', np.zeros((2, 3)))
print('使用eye函式建立的ndarray為:\n ', np.eye(3))
print('使用diag函式建立的ndarray為:\n',np.diag([1, 2, 3, 4]))
print('使用ones函式的ndarray為:\n', np.ones((2, 3)))

# 程式碼 3-4
print('random函式生成的隨機數ndarray為:\n', np.random.random(100))
print('rand函式生成的服從均勻分佈的隨機數ndarray為:\n', np.random.rand(4, 5))
print('randn函式生成的服從正態分佈的隨機數ndarray為:\n', np.random.randn(4, 5))
print('randint函式生成的指定上下限的隨機整數ndarray為:\n',
      np.random.randint(low=2, high=10, size=[2, 5]))

# 程式碼 3-5
arr = np.arange(10)
print('使用元素位置索引結果為:', arr[5])
print('使用元素位置切片結果為:', arr[3:5])
print('省略單個位置切片結果為:', arr[:5])
print('使用元素反向位置切片結果為:', arr[:-1])
arr[2:4] = 100, 101  # 修改對應下標的值
print('修改後的ndarray arr為:', arr)
print('元素位置等差索引結果為:', arr[1:-1:2])
# 步長為負數時,開始位置必須大於結束位置
print('元素位置負數步長等差索引結果為:', arr[5:1:-2])

# 程式碼 3-6
arr = np.array([[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [7, 8, 9, 10, 11]])
print('建立的二維ndarray arr為:\n', arr)
print('切片結果為:', arr[0, 3:5])   # 訪問第0行中第3和第4列的元素
print('切片結果為:\n', arr[1:, 2:])  # 訪問第1和第2行中第2列、第3列和第4列的元素
print('切片結果為:\n', arr[:, 2])  # 訪問第2列所有的元素
# 索引第1、3行中第2列的元素
mask = np.array([1, 0, 1], dtype=np.bool)
print('使用布林值ndarray索引結果為:', arr[mask, 2])
arr = np.empty((8, 4))

for i in range(8):
    arr[i] = i
print('建立的二維ndarray arr為:\n', arr)
print('以特定順序索引arr結果為:\n', arr[[4, 3, 0, 6]])
print('以特定逆序索引arr結果為:\n', arr[[-3, -5, -7]])
arr = np.array([np.arange(i*4, i*4+4) for i in np.arange(6)])
print('建立的二維ndarray arr為:\n', arr)
# 返回一個ndarray最終的元素(1,0)、(5,3)、(4,1)、(2,2)
print('使用二維ndarray索引arr結果為:', arr[[1, 5, 4, 2], [0, 3, 1, 2]])

# 程式碼 3-7
arr = np.arange(12)  # 建立一維ndarray
print('建立的一維ndarray arr為:', arr)
arr1 = arr.reshape(3, 4)  # 設定ndarray的維度
print('改變形狀後的ndarray arr1為:\n', arr1)
print('形狀改變後ndarray arr1的維度為:', arr1.ndim)

# 程式碼 3-7
arr.resize(2, 6)
print('resize改變原ndarray形狀,ndarray arr變為:\n', arr)
arr.shape = (4, 3)
print('通過重新設定shape屬性後,ndarray arr為:\n', arr)

# 程式碼 3-8
arr = np.arange(12).reshape(3, 4)
print('建立的二維ndarray arr為:\n', arr)
print('ndarray arr橫向展平後為:', arr.ravel())

# 程式碼 3-8
print('ndarray arr使用flatten方法橫向展平後為:', arr.flatten())
print('ndarray arr使用flatten方法縱向展平後為:', arr.flatten('F'))

# 程式碼 3-9
arr1 = np.arange(12).reshape(3, 4)
print('建立的ndarray arr1為:\n', arr1)
arr2 = arr1*3
print('建立的ndarray arr2為:\n', arr2)
print('hstack橫向組合ndarray arr1與arr2為:\n', np.hstack((arr1, arr2)))
print('vstack縱向組合ndarray arr1與arr2為:\n', np.vstack((arr1, arr2)))

# 程式碼 3-9
print('concatenate橫向組合arr1與arr2為:\n', np.concatenate((arr1, arr2), axis=1))
print('concatenate縱向組合arr1與arr2為:\n', np.concatenate((arr1, arr2), axis=0))
print('dstack深度組合arr1與arr2為:\n', np.dstack((arr1, arr2)))

# 程式碼 3-10
arr = np.arange(16).reshape(4, 4)
print('建立的二維ndarray arr為:\n', arr)
print('hsplit橫向分割arr為:\n', np.hsplit(arr, 2))
print('hsplit縱向分割arr為:\n', np.vsplit(arr, 2))
print('split橫向分割arr為:\n', np.split(arr, 2, axis=1))
print('split縱向分割arr為:\n', np.split(arr, 2, axis=0))


# 程式碼 3-11
np.random.seed(42)  #設定隨機種子
arr = np.random.randint(1, 10, size=12).reshape(4, 3)
print('建立的隨機數ndarray arr為:\n', arr)
print('預設排序後ndarray arr為:\n', np.sort(arr))
print('展平排序的ndarray arr為:', np.sort(arr, axis=None))

# 程式碼 3-11
print('橫軸排序後ndarray arr為:\n', np.sort(arr, axis=1))
print('縱軸排序後ndarray arr為:\n', np.sort(arr, axis=0))
print('橫軸排序後arr的下標為:\n', np.argsort(arr, axis=1))
print('展平排序後arr的下標為:', np.argsort(arr, axis=None))

# 程式碼 3-12
arr = np.arange(6, 12).reshape(2, 3)
print('建立的ndarray arr為:\n', arr)

print('ndarray arr中最大元素的索引為:', np.argmax(arr))
print('ndarray arr中最小元素的索引為:', np.argmin(arr))

# 程式碼 3-12
print('ndarray arr中各列最大元素的索引為:', np.argmax(arr, axis=0))
print('ndarray arr中各行最小元素的索引為:', np.argmin(arr, axis=1))

# 程式碼 3-13
arr = np.arange(12).reshape(4,3)
print('建立的ndarray arr為:\n', arr)
print('where輸出ndarray arr滿足條件的下標為:\n', np.where(arr>6))
arr1 = np.arange(12).reshape(3, 4)
print('建立的ndarray arr1為:\n', arr1)
arr2 = np.arange(-12, 0).reshape(3, 4)
print('建立的ndarray arr2為:\n', arr2)
exp = arr1>5
print('arr1大於5的布林ndarray為:\n', exp)


# 程式碼 3-13
print('where函式搜尋符合條件的arr1與arr2為:\n', np.where(exp, arr1, arr2))
arr = np.arange(9).reshape(3,  3)
print('建立的ndarray arr為:\n', arr)
exp = (arr % 2) == 0
print('arr能被2整除的布林ndarray為:\n', exp)
print('arr基於條件exp提取的元素為:\n', np.extract(exp, arr))


import numpy as np
x=np.array([1,2,3])
y=np.array([4,5,6])
print(x+y)

# 程式碼 3-15
import numpy as np
arr = np.arange(-4, 5).reshape(3, 3)
print('建立的ndarray arr為:\n', arr)
print('ndarray arr各元素的相反數為:\n', np.negative(arr))
print('ndarray arr各元素的絕對值為:\n', np.absolute(arr))
print('ndarray arr各元素的符號為:\n', np.sign(arr))
print('ndarray arr各元素的平方根為:\n', np.sqrt(arr))
print('ndarray arr各元素的自然對數為:\n', np.log(arr))

# 程式碼 3-16
arr = np.arange(20).reshape(4, 5)
print('建立的ndarray arr為:\n', arr)
print('ndarray arr各元素的和為:', np.sum(arr))
print('ndarray arr各行的極差為:', np.ptp(arr, axis=1))
print('ndarray arr各列的均值為:', np.mean(arr, axis=0))
print('ndarray arr的中位數為:', np.median(arr))


# 程式碼 3-16
print('ndarray arr各行的上四分位數為:',np.percentile(arr, 75, axis =1))
print('ndarray arr各列的下四分位數為:', np.percentile(arr, 25, axis =0))
print('ndarray arr的標準差為:', np.std(arr))
print('ndarray arr的方差為:', np.var(arr))
print('ndarray arr的最小值為:', np.min(arr))
print('ndarray arr的最大值為:', np.max(arr))

# 程式碼 3-17
arr = np.arange(1, 11)
print('建立的ndarray arr為:', arr)
print('ndarray arr的元素累計和為:', np.cumsum(arr))
print('ndarray arr的元素累計積為:\n', np.cumprod(arr))

# # 程式碼 3-18
# import numpy as np
# arr = np.load('../data/arr.npy')
# print('從二進位制檔案arr.npy讀取的ndarray arr為:\n', arr)
# arr1 = np.load('../data/arr.npz')
# print('從二進位制檔案arr.npz讀取的第1個ndarray為:\n', arr1['arr_0'])
# print('從二進位制檔案arr.npz讀取的第2個ndarray為:\n', arr1['arr_1'])

# # 程式碼 3-19
# np.random.seed(123)
# arr = np.random.rand(25).reshape(5, 5)
# print('建立的ndarray arr為:\n', arr)

# np.save('../tmp/save_arr.npy', arr)
# print('……儲存成功……')

# # 程式碼 3-20
# arr1 = np.random.rand(36).reshape(6, 6)
# print('建立的ndarray arr1為:\n', arr1)
# arr2 = np.random.rand(16).reshape(4, 4)
# print('建立的ndarray arr2為:\n', arr2)
# np.savez('../tmp/save_arr.npz', arr1, arr2)

# # 程式碼 3-20
# arr3 = np.load('../tmp/save_arr.npz')
# print('存取的第1個ndarray為:\n', arr3['arr_0'])
# np.savez('../tmp/save_kwds.npz', x=arr1, y=arr2)
# arr4 = np.load('../tmp/save_kwds.npz')
# print('存取的第2個ndarray為:\n', arr4['y'])

# # 程式碼 3-21
# # 指定分隔符讀入文字檔案
# arr = np.loadtxt("../data/arr.txt", delimiter=",")
# print('讀取的ndarray arr為:\n', arr1)

# arr = np.arange(36).reshape(6, 6)
# print('建立的ndarray arr為:', arr)

# np.savetxt("../tmp/savetxt.txt", arr, fmt="%d", delimiter=",")
# print('……儲存成功……')

# 程式碼 3-23
import pandas as pd
list1=[0,1,2,3,4]
series = pd.Series(list1, index = ['a', 'b', 'c', 'd', 'e'], name = 'list')
print('Series位於第1位置的資料為:', series[0])
print('Series中Index為a的資料為:', series['a'])
bool = (series < 4)
print('bool型別的Series為:\n', bool)
print('通過bool資料訪問Series結果為:\n', series[bool])

# 程式碼 3-24
# 更新元素
series['a'] = 3
print('更新後的Series為:\n', series)
series1 = pd.Series([4, 5], index = ['f', 'g'])
# 追加Series
print('在series插入series1後為:\n', series.append(series1))
# 新增單個數據
series1['h'] = 7
print('在series1插入單個數據後為:\n', series1)
# 刪除資料
series.drop('e', inplace = True)
print('刪除索引e對應資料後的series為:\n', series)

# 程式碼 3-25
dict1 = {'col1': [0, 1, 2, 3, 4], 'col2': [5, 6, 7, 8, 9]}
print('通過dict建立的DataFrame為:\n', pd.DataFrame(dict1, index = ['a', 'b', 'c', 'd', 'e']))

list2 = [[0, 5], [1, 6], [2, 7], [3, 8], [4, 9]]
print('通過list建立的DataFrame為:\n',
      pd.DataFrame(list2, index = ['a', 'b', 'c', 'd', 'e'], columns = ['col1', 'col2']))

# 程式碼 3-26
df = pd.DataFrame({'col1': [0, 1, 2, 3, 4], 'col2': [5, 6, 7, 8, 9]},
                   index = ['a', 'b', 'c', 'd', 'e'])
print(df)
print('DataFrame的Index為:', df.index)
print('DataFrame的列標籤為:', df.columns)
print('DataFrame的軸標籤為:', df.axes)
print('DataFrame的維度為:', df.ndim)
print('DataFrame的形狀為:', df.shape)

# 程式碼 3-28
# 更新列
df['col1'] = [10, 11, 12, 13, 14]
print('更新列後的DataFrame為:\n', df)
# 插入列
df['col3'] = [15, 16, 17, 18, 19]
print('插入列後的DataFrame為:\n', df)


# 程式碼 3-28
# 刪除列
df.drop(['col3'], axis = 1, inplace = True)
print('刪除col3列後的DataFrame為:\n', df)
# 刪除行
df.drop('a', axis = 0, inplace = True)
print('刪除a行後的DataFrame為:\n', df)

# 程式碼 3-29
df = pd.DataFrame({'col1': [0, 1, 2, 3, 4], 'col2': [5, 6, 7, 8, 9]},    index = ['a', 'b', 'c', 'd', 'e'])
print('建立的DataFrame為:\n', df)

# 訪問單列資料
print('DataFrame中col1列資料為:\n', df['col1'])

# 以屬性的方式訪問單列資料
print('DataFrame中col1列資料為:\n', df.col1)

# 程式碼3-30
# 訪問單列多行資料
print('DataFrame中col1列前3行資料為:\n', df['col1'][0: 3])

# 訪問多列多行資料
print('DataFrame中col1列、col2列前3行資料為:\n', df[['col1', 'col2']][0: 3])

# 訪問多行資料
print('DataFrame的前3行為:\n', df[: ][0: 3])

# 程式碼 3-31
# 訪問單列資料
print('DataFrame中col1列資料為:\n', df.loc[: , 'col1'])
# 訪問多列資料
print('DataFrame中col1列、col2資料為:\n', df.loc[: , ['col1', 'col2']])
# 訪問單行資料
print('DataFrame中a行對應資料為:\n', df.loc['a', :])
# 訪問多行資料
print('DataFrame中a行、b行對應資料為:\n', df.loc[['a', 'b'], :])
# 行列結合訪問資料
print('DataFrame中a行、b行,col1列、col2列對應的資料為:\n',
      df.loc[['a', 'b'], ['col1', 'col2']])
# 接收bool資料
print('DataFrame中col1列大於0的資料為:\n', df.loc[df['col1'] > 0, :])
# 接收函式
print('DataFrame中col1列大於0的資料為:\n', df.loc[lambda df: df['col1'] > 0, :])

# 程式碼 3-32
# 訪問單列資料
print('DataFrame中col1列資料為:\n', df.iloc[: , 0])
# 訪問多列資料
print('DataFrame中col1列、col2列資料為:\n', df.iloc[: , [0, 1]])
# 訪問單行資料
print('DataFrame中a行資料為:\n', df.iloc[0, :])
# 訪問多行資料
print('DataFrame中a行、b行資料為:\n', df.iloc[[0, 1], :])
# 行列結合訪問資料
print('DataFrame中a行、b行,col1列、col2列資料為:\n', df.iloc[[0, 1], [0, 1]])

# 程式碼 3-33
multiindex = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
              ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
df1 = pd.DataFrame(np.arange(16).reshape(8, 2),
                   index=multiindex, columns=['column1', 'column2'])
print('建立的DataFrame為:\n', df1)

print('DataFrame的層次化索引為:\n', df1.index)

# 程式碼 3-34
print('訪問DataFrame第1索引層bar,第2索引層two結果為:\n',
      df1.loc[('bar', 'two'), :])

print('訪問DataFrame第1索引層bar、baz、foo,第2索引層one、two結果為:\n',
      df1.loc[(['bar', 'baz', 'foo'], ['one', 'two']), :])

print('訪問DataFrame第1索引層bar、baz、foo,第2索引層one、two結果為:\n',
      df1.loc[(slice('bar', 'foo'), slice(None)), :])

# 程式碼 3-35
# 接收單個標籤
idx = pd.IndexSlice
print('訪問DataFrame第1索引層bar,第2索引層two結果為:\n', df1.loc[idx['bar', 'two'], :])

# 接收標籤list
print('訪問DataFrame第1索引層bar、foo,第2索引層two結果為:\n',
      df1.loc[idx[['bar', 'foo'], 'two'], :])

# 接收標籤切片
print('訪問DataFrame第1索引層bar到foo,第2索引層two結果為:\n',
      df1.loc[idx['bar': 'foo', 'one'], :])

# 接收bool陣列
con = df1['column1']>0
print('訪問DataFrame第1索引層bar到foo,第二索引層對應的'
      'column1列大於0結果為:\n',df1.loc[idx['bar': 'foo', con], :])

# 程式碼 3-36
# 按行索引排序
print('按行索引排序後的DataFrame為:\n', df.sort_index(axis = 0))
# 按列索引降序排列
print('按列索引降序排列後的DataFrame為:\n', df.sort_index(axis = 1, ascending = False))
# 按列排序
print('按col2列排序後的DataFrame為:\n', df.sort_values('col2'))
# 按行降序排列
print('按列降序排列後的DataFrame為:\n', df.sort_values('a', axis = 1, ascending = False))

print('按col2列排序,返回前2個最小值:\n', df.nsmallest(2, 'col2'))

print('按col2列排序,返回前2個最大值:\n', df.nlargest(2, 'col2'))

# 程式碼 3-37
df2 = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'], 
                    'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
df3 = pd.DataFrame({'key': ['K0', 'K1', 'K2'], 'B': ['B0', 'B1', 'B2']})
# 橫向堆疊df2、df3
print('橫向堆疊df2、df3後的DataFrame為:\n', pd.concat([df2, df3], axis = 1))

# 橫向堆疊(內連)df2、df3
print('橫向堆疊(內連)df2、df3後的DataFrame為:\n',
      pd.concat([df2, df3], axis = 1, join = 'inner'))

# 程式碼 3-38
print('橫向堆疊df2、df3後的DataFrame為:\n', df2.join(df3, rsuffix = '_2'))
# 縱向堆疊df2、df3
print('縱向堆疊df2、df3後的DataFrame為:\n', pd.concat([df2, df3], axis = 0))

# 縱向堆疊(內連)df2、df3
print('縱向堆疊(內連)df2、df3後的DataFrame為:\n',
      pd.concat([df2, df3], axis = 0, join = 'inner'))
print('縱向堆疊df2、df3後的DataFrame為:\n', df2.append(df3))

# 程式碼 3-39
print('以列key為鍵,內連df2、df3後的DataFrame為:\n',
pd.merge(df2, df3, on = 'key', how = 'inner'))

# # 程式碼 3-40
# df = pd.read_csv('../data/meal_order_info.csv', encoding = 'gbk')
# print('讀取的CSV檔案前5行資料為:\n', df.head())


#  # 程式碼 3-42
# df = pd.read_excel('../data/users_info.xlsx', encoding = 'gbk')
# print('讀取的Excel檔案前5行資料為:\n', df.head())


# 程式碼 3-43
import matplotlib.pyplot as plt
X=np.random.randn(100)
Y=np.random.randn(100)
plt.scatter(X,Y)

#程式碼3-44
years=[1950,1960,1970,1980,1990,2000,2010]
gdp=[300.2,543.3,1075.9,2862.5,5979.6,10289.7,14958.3]
plt.plot(years,gdp,color='r')

#程式碼3-45
data=np.random.randint(1,10,10)
data
plt.pie(data)

#程式碼3-46
x=np.random.normal(size=100)
plt.hist(x,bins=30)

#程式碼3-47
data=[23,85,72,43,52]
plt.bar([1,2,3,4,5],data)

#程式碼3-48
list10=np.random.randint(1,100,10)
plt.boxplot(list10)

# 程式碼 3-42
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize = (6, 6), dpi = 80)  # 建立畫布。大小為6×6,畫素為80
x = np.linspace(0, 1, 1000)
fig.add_subplot(2, 1, 1)  # 分為2×1圖形陣,選擇第1張圖片繪圖
plt.title('y=x^2 & y=x')  # 新增標題
plt.xlabel('x')  # 新增x軸名稱‘x’
plt.ylabel('y')  # 新增y軸名稱‘y’
plt.xlim((0, 1))  # 指定x軸範圍(0,1)
plt.ylim((0, 1))  # 指定y軸範圍(0,1)
plt.xticks([0, 0.3, 0.6, 1])  # 設定x軸刻度
plt.yticks([0, 0.5, 1])  # 設定y軸刻度
plt.plot(x, x ** 2)
plt.plot(x, x)
plt.legend(['y=x^2', 'y=x'])  # 新增圖例


#程式碼3-49
fig=plt.figure(figsize=(10,6))
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax4=fig.add_subplot(2,2,4)
ax1.scatter(years,gdp)
ax2.plot(years,gdp)
ax3.bar(years,gdp)
ax4.hist(years,gdp)


# 三維曲面
import matplotlib.pyplot as plt
import numpy as np

x,y=np.mgrid[-2:2:20j,-2:2:20j]
z=50*np.sin(x+y*2)

ax=plt.subplot(111,projection='3d')
ax.plot_surface(x,y,z,rstride=3,cstride=2,cmap=plt.cm.coolwarm)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# 三維柱狀圖
x=np.random.randint(0,40,10)
y=np.random.randint(0,40,10)
z=80*abs(np.sin(x+y))

ax=plt.subplot(projection='3d')
ax.bar3d(x,y,np.zeros_like(z),dx=1,dy=1,dz=z,color='red')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')


# 三維散點圖
x=np.random.randint(0,40,30)
y=np.random.randint(0,40,30)
z=np.random.randint(0,40,30)

ax=plt.subplot(projection='3d')
for xx,yy,zz in zip(x,y,z):
    color='r'
    if 10<zz<20:
        color='b'
    elif zz>=20:
        color='g'
    ax.scatter(xx,yy,zz,c=color,marker='*',s=160,linewidth=1,edgecolor='b')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

#程式碼4-1
import pandas as pd
df = pd.read_html('http://worldcup.2014.163.com/schedule/')

# #程式碼4-2
# import requests
# from bs4 import BeautifulSoup
# data = []
# wb_data = requests.get('http://www.kugou.com/yy/rank/home/1-8888.html')
# soup = BeautifulSoup(wb_data.text,'lxml')
# ranks = soup.select('span.pc_temp_num')
# titles = soup.select('div.pc_temp_songlist > ul > li > a')
# times = soup.select('span.pc_temp_tips_r > span')

# for rank,title,time in zip(ranks,titles,times):
#     a = {
#         'rank':rank.get_text().strip(),
#         'singer':title.get_text().split('-')[0],
#         'song':title.get_text().split('-')[1],
#         'time':time.get_text().strip()
#     }
#     data.append(a)

# #程式碼4-3
# import json
# f = open('D:/data/eueo2012.json')
# obj = f.read()
# result = json.loads(obj)
# result

# 程式碼4-5
import numpy as np
df1=pd.DataFrame([[3,5,3],[1,6,np.nan],['lili',np.nan,'pop'],[np.nan,'a','b']])

print(df1.isnull().sum())
df1.isnull().sum().sum()

#程式碼4-7
data={'name':['張颯','李蘇','張颯','萬明'],    'sex':['female','male','female','male'],
      'year':[2001,2002,2001,2002],
      'city':['北京','上海','北京','北京']}
df3=pd.DataFrame(data)
df3.duplicated()
df3.drop_duplicates()
df3.drop_duplicates(keep='last')

#程式碼4-8
data1={'name':['張颯','李蘇','張颯','萬明'],
      'sex':['female','male','','male'],
      'year':[2001,2002,2001,2002],
      'city':['北京','上海','','北京']}
df4=pd.DataFrame(data1)
df4.replace('','不詳')
df4.replace(['',2001],['不詳',2002])
df4.replace({'':'不詳',2001:2002})


#程式碼4-9
data2={'name':['張三','李四','王五','小明'],
       'math':[79,52,63,92]}
df5=pd.DataFrame(data2)
def f(x):
    if x>=90:
        return '優秀'
    elif x>=70:
        return '良好'
    elif x>=60:
        return '合格'
    else:
        return '不合格'
df5['class']=df5['math'].map(f)

#程式碼4-10
df6=pd.DataFrame(np.arange(10),columns=['X'])
df6['Y']=2*df6['X']+0.5
df6.iloc[9,1]=185
df6.plot(kind='scatter',x='X',y='Y')

#程式碼4-11
df7=pd.DataFrame({'朝向':['東','南','東','西','北'],
               '價格':[1200,2100,2300,2900,1400]})
pd.get_dummies(df7['朝向'])

#程式碼4-12
from pandas import Series
df8=pd.DataFrame({'朝向':['東/北','西/南','東','西/北','北'],
               '價格':[1200,2100,2300,2900,1400]})
dummy=df8['朝向'].apply(lambda x:Series(x.split('/')).value_counts())

#程式碼4-13
price=pd.DataFrame({'fruit':['apple','banana','orange'],
                 'price':[23,32,45]})
amount=pd.DataFrame({'fruit':['apple','banana','apple','apple','banana','pear'],
                  'amount':[5,3,6,3,5,7]})
pd.merge(amount,price)
pd.merge(amount,price,how='left')
pd.merge(amount,price,how='right')
pd.merge(amount,price,how='outer')

#程式碼4-14
s1=Series([0,1],index=['a','b'])
s2=Series([2,3],index=['c','d'])
s3=Series([4,5],index=['e','f'])
pd.concat([s1,s2,s3])
pd.concat([s1,s2,s3],axis=1)


#程式碼4-15
import pandas as pd
import numpy as np
df10=pd.DataFrame({'a':[3.0,np.nan,6.0,np.nan],'b':[np.nan,4.0,6.0,np.nan]})
df11=pd.DataFrame({'a':[0,1,2,3,4],'b':[0,1,2,3,4]})
df10.combine_first(df11)

df10=pd.DataFrame({'a':[3.0,np.nan,6.0,np.nan],'b':[np.nan,4.0,6.0,np.nan]})
df11=pd.DataFrame({'a':[0,1,2,3,4],'b':[0,1,2,3,4]})

df10.combine_first(df11)

#程式碼4-16
from pandas import Series,DataFrame
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt 
import matplotlib as mpl
import seaborn as sns  #匯入seaborn繪相簿
iris_data = pd.read_csv(open(r'E:\資料\資料集\seaborn-data-master\iris.csv'))
iris_data.head()
iris_data.shape
iris_data.describe()

# iris_data['class'].unique()
# iris_data.ix[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
# iris_data.ix[iris_data['class'] == 'Iris-setossa', 'class'] = 'Iris-setosa'
# iris_data['class'].unique()
# sns.pairplot(iris_data, hue='class')
# iris_data.ix[iris_data['class'] == 'Iris-setosa', 'sepal_width_cm'].hist()
# iris_data = iris_data.loc[(iris_data['class'] != 'Iris-setosa') | (iris_data['sepal_width_cm'] >= 2.5)]
# iris_data.loc[iris_data['class'] == 'Iris-setosa', 'sepal_width_cm'].hist()

# iris_data.loc[(iris_data['class'] == 'Iris-versicolor') &
#               (iris_data['sepal_length_cm'] < 1.0)]
# iris_data.loc[(iris_data['class'] == 'Iris-versicolor') &
#               (iris_data['sepal_length_cm'] < 1.0),
#               'sepal_length_cm'] *= 100.0
# iris_data.isnull().sum()
# iris_data[iris_data['petal_width_cm'].isnull()]
# iris_data.dropna(inplace=True)
# iris_data.to_csv('H:\python資料分析\資料\iris-clean-data.csv', index=False)
# iris_data = pd.read_csv(open('H:\python資料分析\資料\iris-clean-data.csv'))
# iris_data.head()

# iris_data.shape
# sns.pairplot(iris_data, hue='class')
# iris_data.boxplot(column='petal_length_cm', by='class',grid=False,figsize=(6,6))

# # 程式碼 4-17
# import pandas as pd
# import numpy as np
# df = pd.read_csv('D:/data/Concrete.csv', encoding = 'gbk')
# print('資料框df每列對應的最大值為:\n', np.max(df), '\n', '資料框df每列對應的最小值為:\n', np.min(df))
# print('資料框df每列對應的均值為:\n', np.mean(df))
# print('資料框df對應的中位數為:', np.median(df))
# print('資料框df每列對應的標準差為:\n', np.std(df))
# print('資料框df每列對應的方差為:\n', np.var(df))

# # 程式碼 4-18
# print('資料框df每列對應的最大值為:\n', df.max(), '\n','資料框df每列對應的最小值為:\n', df.min())
# print('資料框df每列對應的均值為:\n', df.mean())
# print('資料框df每列對應的中位數為:\n', df.median())
# print('資料框df每列對應的標準差為:\n', df.std())
# print('資料框df每列對應的方差為:\n', df.var())
# print('使用describe方法的描述性統計結果為:\n', df.describe())


# # 程式碼 4-19
# df1 = pd.DataFrame({'col1': list('abca'), 'col2': list('bccd')}, dtype = 'category')
# print('使用describe方法的描述性統計結果為:\n', df1.describe())
# print('DataFrame的info資訊為:\n')
# df.info()

# # 程式碼 4-20
# station = pd.read_csv('D:/data/Station.csv', encoding = 'gbk')
# group = station.groupby('station')
# print('以station為分組鍵,建立的GroupBy物件為:\n', group)

# print('分組資料的均值前5行結果為:\n', group.mean().head())
# print('分組資料的和前5行結果為:\n',group.sum().head())
# print('分組資料的最大值前5行結果為:\n',group.max().head())

# # 程式碼 4-21
# print('分組的均值前5行結果為:\n', group.agg(np.mean).head())
# def f(x):
#     return x.max() - x.min()
# group1 = group.agg(f)
# print('分組的極差前5行結果為:\n', group1.head())
# group2 = group.agg([np.mean, np.sum])
# print('分組的均值和總和前5行結果為:\n', group2.head())
# group3 = group.agg({'on_man': np.mean, 'off_man': np.sum})
# print('列on_man應用均值函式,列off_man應用匯總函式前5行結果為:\n', group3.head())


# # 程式碼 4-22
# print('分組的均值前5行結果為:\n', group.apply(np.mean).head())

# def f(x):
#     result = x[0: 2]
#     return result
# print('分組的前兩個資料前5行結果為:\n', group.apply(f).head())

# # 程式碼 4-23
# print('對分組應用均值函式,返回的DataFrame前5行資料為:\n',
#       group.transform(np.mean).head())

# def f(x):
#     result = x*2
#     return result
# print('對分組的每個元組乘以2,返回的DataFrame前5行資料為:\n',   group.transform(f).head())

# 程式碼 4-24
dit = {'one': ['a', 'b', 'b', 'b', 'a'], 'two': [0, 1, 2, 3, 4],
     'three': [5, 6, 7, 8, 9], 'four': ['x', 'x', 'y', 'y', 'y']}
df = pd.DataFrame(dit)
tdf = pd.pivot_table(df, index=['four'], columns=['one'])
print('建立的透視表為:\n', tdf)

tdf = pd.pivot_table(df, index=['four'], columns=['one'], aggfunc = np.sum)
print('分組和的透視表為:\n', tdf)
# 程式碼 4-25
cdf = pd.crosstab(index = df['four'], columns = df['one'])
print('建立的交叉表為:\n', cdf)

cdf = pd.pivot_table(df, values = 'two', index = ['four'], columns = ['one'], 
                     aggfunc = (lambda x: len(x)))
print('使用pivot_table函式建立的交叉表為:\n', cdf)


導包
import numpy as np
建立二維陣列
x = np.matrix([[1,2,3],[4,5,6]])
建立一維陣列
y = np.matrix([1,2,3,4,5,6])
x 的第二行第二列元素
x[1,1]
矩陣的乘法
x*y
複製程式碼
# 相關係數矩陣,可使用在列表元素陣列矩陣
# 負相關
np.corrcoef([1,2,3],[8,5,4])
'''
array([[ 1.        , -0.96076892],
       [-0.96076892,  1.        ]])
'''
# 正相關
np.corrcoef([1,2,3],[4,5,7])
'''
array([[1.        , 0.98198051],
       [0.98198051, 1.        ]])
'''
複製程式碼
矩陣的方差
np.cov([1,1,1,1,1])
矩陣的標準差
np.std([1,1,1,1,1])
垂直堆疊矩陣
z = np.vstack((x,y))
矩陣的協方差
np.cov(z)
np.cov(x,y)
標準差
np.std(z)
列向標準差
np.std(z,axis = 1)
方差
np.cov(x)
特徵值和特徵向量
A = np.array([[1,-3,3],[3,-5,3],[6,-6,4]])
e,v = np.linalg.eig(A)
e 為特徵值, v 為特徵向量
矩陣與特徵向量的乘積
np.dot(A,v)
特徵值與特徵向量的乘積
e * v
驗證兩個乘積是否相等
np.isclose(np.dot(A,v),(e * v))
行列式 |A - λE| 的值應為 0
np.linalg.det(A-np.eye(3,3)*e)
逆矩陣
y = np.linalg.inv(x)
複製程式碼
矩陣的乘法(注意先後順序)
x * y
'''
matrix([[ 1.00000000e+00,  5.55111512e-17,  1.38777878e-17],
        [ 5.55111512e-17,  1.00000000e+00,  2.77555756e-17],
        [ 1.77635684e-15, -8.88178420e-16,  1.00000000e+00]])
'''
y * x
'''
matrix([[ 1.00000000e+00, -1.11022302e-16,  0.00000000e+00],
        [ 8.32667268e-17,  1.00000000e+00,  2.22044605e-16],
        [ 6.93889390e-17,  0.00000000e+00,  1.00000000e+00]])
'''
複製程式碼
求解線性方程組
a = np.array([[3,1],[1,2]])
b = np.array([9,8])
x = np.linalg.solve(a,b)
最小二乘解:返回解,餘項,a 的秩,a 的奇異值
np.linalg.lstsq(a,b)
# (array([2., 3.]), array([], dtype=float64), 2, array([3.61803399, 1.38196601]))
複製程式碼
計算向量和矩陣的範數
x = np.matrix([[1,2],[3,-4]])

np.linalg.norm(x)
# 5.477225575051661

np.linalg.norm(x,-2)
# 1.9543950758485487

np.linalg.norm(x,-1)
# 4.0

np.linalg.norm(x,1)
# 6.0

np.linalg.norm([1,2,0,3,4,0],0)
# 4.0

np.linalg.norm([1,2,0,3,4,0],2)
# 5.477225575051661
複製程式碼
複製程式碼
奇異值分解
a = np.matrix([[1,2,3],[4,5,6],[7,8,9]])

u,s,v = np.linalg.svd(a)

u
'''
matrix([[-0.21483724,  0.88723069,  0.40824829],
        [-0.52058739,  0.24964395, -0.81649658],
        [-0.82633754, -0.38794278,  0.40824829]])
'''
s
'''
array([1.68481034e+01, 1.06836951e+00, 4.41842475e-16])
'''
v
'''
matrix([[-0.47967118, -0.57236779, -0.66506441],
        [-0.77669099, -0.07568647,  0.62531805],
        [-0.40824829,  0.81649658, -0.40824829]])
'''

# 驗證
u * np.diag(s) * v
'''
matrix([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]])
'''
複製程式碼
實現矩陣的轉置
x.T
元素平均值
x.mean()
縱向平均值
x.mean(axis = 0)
橫向平均值
x.mean(axis = 1)
所有元素之和
x.sum()
橫向最大值
x.max(axis = 1)
橫向最大值的索引下標
x.argmax(axis = 1)
對角線元素
x.diagonal()
非零元素下標
x.nonzero()
建立陣列

np.array([1,2,3,4])
np.array((1,2,3,4))
np.array(range(4)) # 不包含終止數字
# array([0, 1, 2, 3])
# 使用 arange(初始位置=0,末尾,步長=1)
np.arange(1,8,2)
# array([1, 3, 5, 7])
生成等差陣列,endpoint 為 True 則包含末尾數字
np.linspace(1,3,4,endpoint=False)
# array([1. , 1.5, 2. , 2.5])
np.linspace(1,3,4,endpoint=True)
# array([1.        , 1.66666667, 2.33333333, 3.        ])
建立全為零的一維陣列
np.zeros(3)
建立全為一的一維陣列
np.ones(4)
np.linspace(1,3,4)
# array([1.        , 1.66666667, 2.33333333, 3.        ])
複製程式碼
np.logspace(起始數字,終止數字,數字個數,base = 10) 對數陣列
np.logspace(1,3,4)
# 相當於 10 的 linspace(1,3,4) 次方
# array([  10.        ,   46.41588834,  215.443469  , 1000.        ])



np.logspace(1,3,4,base = 2)
# 2 的 linspace(1,3,4) 次方
# array([2.       , 3.1748021, 5.0396842, 8.       ])
複製程式碼
建立二維陣列(列表巢狀列表)
np.array([[1,2,3],[4,5,6]])
# 建立全為零的二維陣列
# 兩行兩列
np.zeros((2,2))
三行兩列
np.zeros((3,2))
複製程式碼
# 建立一個單位陣列
np.identity(3)

'''
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
'''
複製程式碼
複製程式碼
建立一個對角矩陣,(引數為對角線上的數字)
np.diag((1,2,3))

'''
array([[1, 0, 0],
       [0, 2, 0],
       [0, 0, 3]])
'''
複製程式碼
第一行元素
n[0]
第一行第三列元素
n[0,2]
第一行和第二行的元素
n[[0,1]]
第一行第三列,第三行第二列,第二行第一列
n[[0,2,1],[2,1,0]]
將陣列倒序
a[::-1]
步長為 2
a[::2]
從 0 到 4 的元素
a[:5]
複製程式碼
變換 c 的矩陣行和列

c = np.arange(16)
# array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])

c.shape = 4,4
'''
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
'''
複製程式碼
第一行,第三個元素到第五個元素(如果沒有則輸出到末尾截止)
c[0,2:5]
第二行元素
c[1]
第三行到第六行,第三列到第六列
c[2:5,2:5]
第二行第三列元素和第三行第四列元素
c[[1,2],[2,3]]
第一行和第三行的第二列到第三列的元素
c[[0,2],1:3]
第一列和第三列的所有橫行元素
c[:,[0,2]]
第三列所有元素
c[:,2]
第二行和第四行的所有元素
c[[1,3]]
第一行的第二列,第四列元素,第四行的第二列,第四列元素
c[[0,3]][:,[1,3]]
使用 * 進行相乘
x*2
使用 / 進行相除
x / 2
2 / x
使用 // 進行整除
x//2
10//x
使用 ** 進行冪運算
x**3
2 ** x
使用 + 進行相加
x + 2
使用 % 進行取模
x % 3
使用 + 進行相加
np.array([1,2,3,4]) + np.array([11,22,33,44])


np.array([1,2,3,4]) + np.array([3])
# array([4, 5, 6, 7])
陣列的內積運算(對應位置上元素相乘)
np.dot(x,y)
sum(x*y)
將陣列中大於 0.5 的元素顯示
n[n>0.5]
找到陣列中 0.05 ~ 0.4 的元素總數
sum((n > 0.05)&(n < 0.4))
是否都大於 0.2
np.all(n > 0.2)
是否有元素小於 0.1
np.any(n < 0.1)
複製程式碼
在 a 中是否有大於 b 的元素
a > b
# array([False,  True, False])

# 在 a 中是否有等於 b 的元素
a == b
# array([False, False,  True])

# 顯示 a 中 a 的元素等於 b 的元素
a[a == b]
# array([7])
複製程式碼
顯示 a 中的偶數且小於 5 的元素
a[(a%2 == 0) & (a < 5)]
生成一個隨機陣列
np.random.randint(0,6,3)
生成一個隨機陣列(二維陣列)
np.random.randint(0,6,(3,3))
生成十個隨機數在[0,1)之間
np.random.rand(10)
'''
array([0.9283789 , 0.43515554, 0.27117021, 0.94829333, 0.31733981,
       0.42314939, 0.81838647, 0.39091899, 0.33571004, 0.90240897])
'''
從標準正態分佈中隨機抽選出3個數
np.random.standard_normal(3)
返回三頁四行兩列的標準正態分佈數
np.random.standard_normal((3,4,2))
x = np.arange(8)
在陣列尾部追加一個元素
np.append(x,10)
在陣列尾部追加多個元素
np.append(x,[15,16,17])
使用 陣列下標修改元素的值
x[0] = 99
在指定位置插入資料
np.insert(x,0,54)
建立一個多維陣列
x = np.array([[1,2,3],[11,22,33],[111,222,333]])

修改第 0 行第 2 列的元素值
x[0,2] = 9
行數大於等於 1 的,列數大於等於 1 的置為 1
x[1:,1:] = 1
複製程式碼
# 同時修改多個元素值
x[1:,1:] = [7,8]
'''
array([[  1,   2,   9],
       [ 11,   7,   8],
       [111,   7,   8]])
'''
x[1:,1:] = [[7,8],[9,10]]
'''
array([[  1,   2,   9],
       [ 11,   7,   8],
       [111,   9,  10]])
'''
複製程式碼
檢視陣列的大小
n.size
將陣列分為兩行五列
n.shape = 2,5
顯示陣列的維度
n.shape
設定陣列的維度,-1 表示自動計算
n.shape = 5,-1
將新陣列設定為呼叫陣列的兩行五列並返回
x = n.reshape(2,5)
複製程式碼
x = np.arange(5)
# 將陣列設定為兩行,沒有數的設定為 0
x.resize((2,10))
'''
array([[0, 1, 2, 3, 4, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
'''


# 將 x 陣列的兩行五列形式顯示,不改變 x 的值
np.resize(x,(2,5))
'''
array([[0, 1, 2, 3, 4],
       [0, 0, 0, 0, 0]])
'''
複製程式碼
x = np.array([1,4,5,2])
# array([1, 4, 5, 2])

# 返回排序後元素的原下標
np.argsort(x)
# array([0, 3, 1, 2], dtype=int64)
輸出最大值的下標
x.argmax( )
輸出最小值的下標
x.argmin( )
對陣列進行排序
x.sort( )
每個陣列元素對應的正弦值
np.sin(x)
每個陣列元素對應的餘弦值
np.cos(x)
對引數進行四捨五入
np.round(np.cos(x))
對引數進行上入整數 3.3->4
np.ceil(x/3)
複製程式碼
# 分段函式
x = np.random.randint(0,10,size=(1,10))
# array([[0, 3, 6, 7, 9, 4, 9, 8, 1, 8]])

# 大於 4 的置為 0
np.where(x > 4,0,1)
# array([[1, 1, 0, 0, 0, 1, 0, 0, 1, 0]])

# 小於 4 的乘 2 ,大於 7 的乘3
np.piecewise(x,[x<4,x>7],[lambda x:x*2,lambda x:x*3])
# array([[ 0,  6,  0,  0, 27,  0, 27, 24,  2, 24]])




導包
import pandas as pd
設定輸出結果列對齊
pd.set_option('display.unicode.ambiguous_as_wide',True)
pd.set_option('display.unicode.east_asian_width',True)
建立 從 0 開始的非負整數索引
s1 = pd.Series(range(1,20,5))
使用字典建立 Series 字典的鍵作為索引
s2 = pd.Series({'語文':95,'數學':98,'Python':100,'物理':97,'化學':99})
修改 Series 物件的值
s1[3] = -17
檢視 s1 的絕對值
abs(s1)
將 s1 所有的值都加 5、使用加法時,對所有元素都進行
s1 + 5
在 s1 的索引下標前加入引數值
s1.add_prefix(2)
s2 資料的直方圖
s2.hist()
每行索引後面加上 hany
s2.add_suffix('hany')
檢視 s2 中最大值的索引
s2.argmax()
檢視 s2 的值是否在指定區間內
s2.between(90,100,inclusive = True)
檢視 s2 中 97 分以上的資料
s2[s2 > 97]
檢視 s2 中大於中值的資料
s2[s2 > s2.median()]
s2 與數字之間的運算,開平方根 * 10 保留一位小數
round((s2**0.5)*10,1)
s2 的中值
s2.median()
s2 中最小的兩個數
s2.nsmallest(2)
s2 中最大的兩個數
s2.nlargest(2)
Series 物件之間的運算,對相同索引進行計算,不是相同索引的使用 NaN
pd.Series(range(5)) + pd.Series(range(5,10))
對 Series 物件使用匿名函式
pd.Series(range(5)).pipe(lambda x,y,z :(x**y)%z,2,5)
pd.Series(range(5)).pipe(lambda x:x+3)
pd.Series(range(5)).pipe(lambda x:x+3).pipe(lambda x:x*3)
對 Series 物件使用匿名函式
pd.Series(range(5)).apply(lambda x:x+3)
檢視標準差
pd.Series(range(0,5)).std()
檢視無偏方差
pd.Series(range(0,5)).var()
檢視無偏標準差
pd.Series(range(0,5)).sem()
檢視是否存在等價於 True 的值
any(pd.Series([3,0,True]))
檢視是否所有的值都等價於 True
all(pd.Series([3,0,True]))
建立一個 DataFrame 物件
dataframe = pd.DataFrame(np.random.randint(1,20,(5,3)),
                         index = range(5),
                         columns = ['A','B','C'])
索引為時間序列
dataframe2 = pd.DataFrame(np.random.randint(5,15,(9,3)),
                          index = pd.date_range(start = '202003211126',
                                                end = '202003212000',
                                                freq = 'H'),
                          columns = ['Pandas','爬蟲','比賽'])
使用字典進行建立
dataframe3 = pd.DataFrame({'語文':[87,79,67,92],
                           '數學':[93,89,80,77],
                           '英語':[88,95,76,77]},
                          index = ['張三','李四','王五','趙六'])
建立時自動擴充
dataframe4 = pd.DataFrame({'A':range(5,10),'B':3})
檢視周幾
dff['日期'] = pd.to_datetime(data['日期']).dt.weekday_name
按照周幾進行分組,檢視交易的平均值
dff = dff.groupby('日期').mean().apply(round)
dff.index.name = '周幾'
對姓名和日期進行分組,並進行求和
dff = dataframe.groupby(by = ['姓名','日期'],as_index = False).sum()
將 dff 的索引,列 設定成透視表形式
dff = dff.pivot(index = '姓名',columns = '日期',values = '交易額')
檢視前一天的資料
dff.iloc[:,:1]
交易總額小於 4000 的人的前三天業績
dff[dff.sum(axis = 1) < 4000].iloc[:,:3]
工資總額大於 2900 元的員工的姓名
dff[dff.sum(axis = 1) > 2900].index.values
顯示前兩天每一天的交易總額以及每個人的交易金額
dataframe.pivot_table(values = '交易額',index = '姓名',
                      columns = '日期',aggfunc = 'sum',margins = True).iloc[:,:2]
顯示每個人在每個櫃檯的交易總額
dff = dataframe.groupby(by = ['姓名','櫃檯'],as_index = False).sum()
dff.pivot(index = '姓名',columns = '櫃檯',values = '交易額')
檢視每人每天的上班次數
dataframe.pivot_table(values = '交易額',index = '姓名',columns = '日期',aggfunc = 'count',margins = True).iloc[:,:1]
檢視每個人每天購買的次數
dataframe.pivot_table(values = '交易額',index = '姓名',columns = '日期',aggfunc = 'count',margins = True)
每個人每天上過幾次班
pd.crosstab(dataframe.姓名,dataframe.日期,margins = True).iloc[:,:2]
每個人每天去過幾次櫃檯
pd.crosstab(dataframe.姓名,dataframe.櫃檯)
將每一個人在每一個櫃檯的交易總額顯示出來
pd.crosstab(dataframe.姓名,dataframe.櫃檯,dataframe.交易額,aggfunc='sum')
每個人在每個櫃檯交易額的平均值,金額/天數
pd.crosstab(dataframe.姓名,dataframe.櫃檯,dataframe.交易額,aggfunc = 'mean').apply(lambda  num:round(num,2) )
對 5 的餘數進行分組
dataframe.groupby(by = lambda num:num % 5)['交易額'].sum()
檢視索引為 7 15 的交易額
dataframe.groupby(by = {7:'索引為7的行',15:'索引為15的行'})['交易額'].sum()
檢視不同時段的交易總額
dataframe.groupby(by = '時段')['交易額'].sum()
各櫃檯的銷售總額
dataframe.groupby(by = '櫃檯')['交易額'].sum()
檢視每個人在每個時段購買的次數
count = dataframe.groupby(by = '姓名')['時段'].count()
每個人的交易額平均值並排序
dataframe.groupby(by = '姓名')['交易額'].mean().round(2).sort_values()
每個人的交易額,apply(int) 轉換為整數
dataframe.groupby(by = '姓名').sum()['交易額'].apply(int)
每一個員工交易額的中值
data = dataframe.groupby(by = '姓名').median()
檢視交易額對應的排名
data['排名'] = data['交易額'].rank(ascending = False)
data[['交易額','排名']]
每個人不同時段的交易額
dataframe.groupby(by = ['姓名','時段'])['交易額'].sum()
設定各時段累計
dataframe.groupby(by = ['姓名'])['時段','交易額'].aggregate({'交易額':np.sum,'時段':lambda x:'各時段累計'})
對指定列進行聚合,檢視最大,最小,和,平均值,中值
dataframe.groupby(by = '姓名').agg(['max','min','sum','mean','median'])
檢視部分聚合後的結果
dataframe.groupby(by = '姓名').agg(['max','min','sum','mean','median'])['交易額']
檢視交易額低於 2000 的三條資料
dataframe[dataframe.交易額 < 2000][:3]
檢視上浮了 50% 之後依舊低於 1500 的交易額,檢視 4 條資料
dataframe.loc[dataframe.交易額 < 1500,'交易額'] = dataframe[dataframe.交易額 < 1500]['交易額'].map(lambda num:num*1.5)
檢視交易額大於 2500 的資料
dataframe[dataframe.交易額 > 2500]
檢視交易額低於 900 或 高於 1800 的資料
dataframe[(dataframe.交易額 < 900)|(dataframe.交易額 > 1800)]
將所有低於 200 的交易額都替換成 200
dataframe.loc[dataframe.交易額 < 200,'交易額'] = 200
檢視低於 1500 的交易額個數
dataframe.loc[dataframe.交易額 < 1500,'交易額'].count()
將大於 3000 元的都替換為 3000 元
dataframe.loc[dataframe.交易額 > 3000,'交易額'] = 3000
檢視有多少行資料
len(dataframe)
丟棄缺失值之後的行數
len(dataframe.dropna())
包含缺失值的行
dataframe[dataframe['交易額'].isnull()]
使用固定值替換缺失值
dff = copy.deepcopy(dataframe)
dff.loc[dff.交易額.isnull(),'交易額'] = 999
使用交易額的均值替換缺失值
dff = copy.deepcopy(dataframe)
for i in dff[dff.交易額.isnull()].index:
    dff.loc[i,'交易額'] = round(dff.loc[dff.姓名 == dff.loc[i,'姓名'],'交易額'].mean())
使用整體均值的 80% 填充缺失值
dataframe.fillna({'交易額':round(dataframe['交易額'].mean() * 0.8)},inplace = True)
檢視重複值
dataframe[dataframe.duplicated()]
丟棄重複行
dataframe = dataframe.drop_duplicates()
檢視員工業績波動情況(每一天和昨天的資料作比較)
dff = dataframe.groupby(by = '日期').sum()['交易額'].diff()
對資料使用 map 函式
dff.map(lambda num:'%.2f'%(num))[:5]
檢視張三的波動情況
dataframe[dataframe.姓名 == '張三'].groupby(by = '日期').sum()['交易額'].diff()
修改異常值
data.loc[data.交易額 > 3000,'交易額'] = 3000
data.loc[data.交易額 < 200,'交易額'] = 200
刪除重複值
data.drop_duplicates(inplace = True)
填充缺失值
data['交易額'].fillna(data['交易額'].mean(),inplace = True)
使用交叉表得到每人在各櫃檯交易額的平均值
data_group = pd.crosstab(data.姓名,data.櫃檯,data.交易額,aggfunc = 'mean').apply(round)
繪製柱狀圖
data_group.plot(kind = 'bar')
使用 concat 連線兩個相同結構的 DataFrame 物件
df3 = pd.concat([df1,df2])
合併,忽略原來的索引 ignore_index
df4 = df3.append([df1,df2],ignore_index = True)
按照列進行拆分
df5 = df4.loc[:,['姓名','櫃檯','交易額']]
按照工號進行合併,隨機檢視 3 條資料
rows = np.random.randint(0,len(df5),3)
pd.merge(df4,df5).iloc[rows,:]
按照工號進行合併,指定其他同名列的字尾
pd.merge(df1,df2,on = '工號',suffixes = ['_x','_y']).iloc[:,:]
兩個表都設定工號為索引 set_index
df2.set_index('工號').join(df3.set_index('工號'),lsuffix = '_x',rsuffix = '_y').iloc[:]
按照交易額和工號降序排序,檢視五條資料
dataframe.sort_values(by = ['交易額','工號'],ascending = False)[:5]
按照交易額和工號升序排序,檢視五條資料
dataframe.sort_values(by = ['交易額','工號'])[:5]
按照交易額降序和工號升序排序,檢視五條資料
dataframe.sort_values(by = ['交易額','工號'],ascending = [False,True])[:5]
按工號升序排序
dataframe.sort_values(by = ['工號'])[:5]
按列名升序排序
dataframe.sort_index(axis = 1)[:5]
每隔五天--5D
pd.date_range(start = '20200101',end = '20200131',freq = '5D')
每隔一週--W
pd.date_range(start = '20200301',end = '20200331',freq = 'W')
間隔兩天,五個資料
pd.date_range(start = '20200301',periods = 5,freq = '2D')
間隔三小時,八個資料
pd.date_range(start = '20200301',periods = 8,freq = '3H')
三點開始,十二個資料,間隔一分鐘
pd.date_range(start = '202003010300',periods = 12,freq = 'T')
每個月的最後一天
pd.date_range(start = '20190101',end = '20191231',freq = 'M')
間隔一年,六個資料,年末最後一天
pd.date_range(start = '20190101',periods = 6,freq = 'A')
間隔一年,六個資料,年初最後一天
pd.date_range(start = '20200101',periods = 6,freq = 'AS')
使用 Series 物件包含時間序列物件,使用特定索引
data = pd.Series(index = pd.date_range(start = '20200321',periods = 24,freq = 'H'),data = range(24))
三分鐘重取樣,計算均值
data.resample('3H').mean()
五分鐘重取樣,求和
data.resample('5H').sum()
計算OHLC open,high,low,close
data.resample('5H').ohlc()
將日期替換為第二天
data.index = data.index + pd.Timedelta('1D')
檢視指定日期的年份是否是閏年
pd.Timestamp('20200301').is_leap_year
檢視指定日期所在的季度和月份
day = pd.Timestamp('20200321')
檢視日期的季度
day.quarter
檢視日期所在的月份
day.month
轉換為 python 的日期時間物件
day.to_pydatetime()
檢視所有的交易額資訊
dataframe['交易額'].describe()
檢視四分位數
dataframe['交易額'].quantile([0,0.25,0.5,0.75,1.0])
檢視最大的交易額資料
dataframe.nlargest(2,'交易額')
檢視最後一個日期
dataframe['日期'].max()
檢視最小的工號
dataframe['工號'].min()
第一個最小交易額的行下標
index = dataframe['交易額'].idxmin()
第一個最小交易額
dataframe.loc[index,'交易額']
最大交易額的行下標
index = dataframe['交易額'].idxmax()
跳過 1 2 4 行,以第一列姓名為索引
dataframe2 = pd.read_excel('超市營業額.xlsx',
                           skiprows = [1,2,4],
                           index_col = 1)
檢視 5 到 10 的資料
dataframe[5:11]
檢視第六行的資料
dataframe.iloc[5]
檢視第 1 3 4 行的資料
dataframe.iloc[[0,2,3],:]
檢視第 1 3 4 行的第 1 2 列
dataframe.iloc[[0,2,3],[0,1]]
檢視前五行指定,姓名、時段和交易額的資料
dataframe[['姓名','時段','交易額']][:5]
檢視第 2 4 5 行 姓名,交易額 資料 loc 函式
dataframe.loc[[1,3,4],['姓名','交易額']]
檢視第四行的姓名資料
dataframe.at[3,'姓名']
某一時段的交易總和
dataframe[dataframe['時段'] == '14:00-21:00']['交易額'].sum()
檢視張三總共的交易額
dataframe[dataframe['姓名'].isin(['張三'])]['交易額'].sum()
檢視日用品的銷售總額
dataframe[dataframe['櫃檯'] == '日用品']['交易額'].sum()
檢視交易額在 1500~3000 之間的記錄
dataframe[dataframe['交易額'].between(1500,3000)]
將日期設定為 python 中的日期型別
data.日期 = pd.to_datetime(data.日期)
每七天營業的總額
data.resample('7D',on = '日期').sum()['交易額']
每七天營業總額
data.resample('7D',on = '日期',label = 'right').sum()['交易額']
每七天營業額的平均值
func = lambda item:round(np.sum(item)/len(item),2)
data.resample('7D',on = '日期',label = 'right').apply(func)['交易額']
每七天營業額的平均值
func = lambda num:round(num,2)
data.resample('7D',on = '日期',label = 'right').mean().apply(func)['交易額']
刪除工號這一列
data.drop('工號',axis = 1,inplace = True)
按照姓名和櫃檯進行分組彙總
data = data.groupby(by = ['姓名','櫃檯']).sum()
檢視張三的彙總資料
data.loc['張三',:]
檢視張三在蔬菜水果的交易資料
data.loc['張三','蔬菜水果']
丟棄工號列
data.drop('工號',axis = 1,inplace = True)
按照櫃檯進行排序
dff = data.sort_index(level = '櫃檯',axis = 0)
按照姓名進行排序
dff = data.sort_index(level = '姓名',axis = 0)
按照櫃檯進行分組求和
dff = data.groupby(level = '櫃檯').sum()['交易額']
平均值
data.mean()
標準差
data.std()
協方差
data.cov()
刪除缺失值和重複值,inplace = True 直接丟棄
data.dropna(inplace = True)
data.drop_duplicates(inplace = True)



將 NaN 替換成某一數值
使用 fillna 
dataframe.fillna(value = 'xxx',inplace=True)

刪除某一個值
使用 drop 
dataframe.drop(10,inplace=True)

交換兩行的值

    if m != n:
        temp = np.copy(dataframe[m])
        dataframe[m] = dataframe[n]
        dataframe[n] = temp
    else:
        temp = np.copy(dataframe[dataframe.shape[1]-1])
        dataframe[dataframe.shape[1]-1] = dataframe[n]
        dataframe[n] = temp

刪除 columns 這些列

    dataframe.drop(columns = list, inplace=True)

轉義字元


format格式
'{格式字串}'.format(引數)
格式字串:普通字串和{替換格式符}組成的字串
引數:匹配替換的內容
格式說明標記的語法格式為:
[ [fill] align] [sign] [width] [,] [.precision] [type]
fill:設定填充的字元,可省略,預設為空格;
align:設定對齊方式,^、<、>分別是居中、左對齊、右對齊,可省略,預設右對齊;
sign:設定數值型資料前的符號,+表示須在正數前加正號,-表示在正數前不變,空格表示在正數前加空格,可省略;
width:設定格式化後的字串所佔寬度,可省略;
逗號(,):為數字新增千位分隔符,可省略;
precision:設定數值型資料保留的小數位數,可省略;
type:設定格式化型別
# *填充字元,>右對齊, 6寬度, .2小數位  , f 浮點數格式 
In: '{:*>6.2f}'.format(3.1415926)
Out: '**3.14'

例:使用format格式化字串
# 長度為10,使用二進位制數值,內容居中對齊
In: '{0:^10b}'.format(12)   # 0表示第0個數據,此處可省略
Out: '   1100   '

# 第0個數用百分比,第1個數用科學計演算法,均保留2位小數
In: '{0:.2%}和{1:.2e}'.format(0.1234, 123456)
Out: '12.34%和1.23e+05'

# 長度為10,保留2位小數,使用","千位分隔符,右對齊,長度不夠用“#”填充
In: '{:#>10,.2f}'.format(1234.5678)
Out: '##1,234.57'

IPython magic命令



運算子
算術運算子:-(求負)、+、-、*、/、//、%、**
關係運算符:==、!=、>、>=、<、<=
邏輯運算子:not、and、or
賦值運算子:=、+=、-=、*=、/=、%=、**=、//=
位運算子:&、|、^、~、<<、>>
成員運算子:in、not in
身份運算子:is、is not


常用型別轉換函式

數學方法內建函式


字串常用函式


常用內建函式

math 庫 常用函式

random隨機數函式

time模組
time模組中表示時間的格式主要有三種:
(1)時間戳
時間戳表示是從1970年1月1號 00:00:00開始到現在按秒計算的總秒數。這種時間表示方式廣泛的應用在Unix系統和類Unix系統中。
(2)時間元組
Python在 time 模組內提供了一個 time.struct_time 類,該類代表一個時間物件,它主要包含 9 個屬性:
tm_year、tm_mon、tm_mdayr、tm_hour、tm_min、tm_min、tm_sec、tm_wday、 tm_yday、tm_isdst,
分別表示年、月、日、時、分、秒、周、一年內第幾天和夏實令等。 (3)格式化時間 格式化時間由字母和數字表示的時間,比如:“Sat May 4 15:11:24 2019”。格式化的結構使時間更具可讀性。

t = time.localtime( )    
time.strftime('%Y-%m-%d %H:%M:%S', t)    

datetime模組
datatime模組重新封裝了time模組,它以類的方式提供了多種日期和時間的表達方式
提供的類有:datetime.date、datetime.time、datetime.datetime、datetime.timedelta和datetime.tzinfo。
datetime.datetime類的方法和屬性

列表字典集合常用函式
列表

常用的序列操作函式

字典

修改:

values() 返回所有值
集合

 jieba.lcut方法

jieba庫的作用就是對中文文章進行分詞,提取中文文章中的詞語

cut(字串, cut_all,HMM)
字串是要進行分詞的字串物件
cut_all引數為真表示採用全模式分詞,為假表示採用精確模式分詞,預設值為假;
HMM為真表示採用HMM模型,為假則不採用,預設值為真。

精確模式
jieba.lcut(字串,cut_all=False)

全模式
ieba.lcut(字串,cut_all=True)

HMM 模型 隱馬爾可夫模型

turtle 庫常用函式

int轉換sys,argv引數問題



檔案基本用法
檔案是指儲存在外部儲存器中的一組資訊集合

按照檔案的資料組織形式,檔案分為文字檔案和二進位制檔案兩種

用內建函式open開啟檔案

f = open(檔名, 檔案模式, 編碼方式, 緩衝區大小)

Python預設按作業系統平臺的編碼處理檔案,windows系統預設編碼為GBK,開啟該檔案時需指定這種編碼方式。

寫二進位制檔案時使用pickle模組的dump()函式,一般使用形式如下:

dump(寫入物件, 檔案物件, [,協議])

寫入物件是要寫入檔案的物件,它可以是整數、實數、字串、列表、字典等物件。
檔案物件是函式open()開啟的檔案物件,物件寫入其中。
協議是序列化使用的協議;若該項省略,則預設為0;若為負值或HIGHEST_PROTOCOL,則使用最高的協議版本。
檔案定位

檔案物件的函式tell()返回檔案指標的當前位置
檔案物件的函式seek()把檔案指標移動到新位置

seek(偏移值[,起點])

偏移值表示移動的距離
起點表示從哪裡開始移動,0表示從檔案頭開始,1表示從當前位置開始,2表示從檔案尾開始,預設值為0。

讀/寫docx檔案
安裝 

pip  install  python-docx

1.建立新Word文件
建立新文件需要呼叫Document物件的save方法,
一個Document物件代表一個Word文件,該方法的引數是儲存的檔名。 from docx import Document doc = Document() doc.save("test.docx")

2.新增段落和段落文字
呼叫Document物件的add_paragraph方法,返回值是一個Paragraph物件。
呼叫Paragraph物件的add_run方法為該段落新增文字。add_run方法的返回值是一個Run物件,需要設定該物件屬性。 from docx import Document doc = Document() p = doc.add_paragraph('無格式的部分') p.add_run('加粗部分').bold = True p.add_run('無格式') p.add_run('斜體部分').italic = True doc.save(r".\test.docx") 無格式的部分加粗部分 無格式 斜體部分

3.讀取文件的所有段落
Document物件的paragraphs屬性是一個包含文件所有Paragraph物件的列表物件,
一個Paragraph物件代表文件的一個段落。對paragraphs屬性進行迴圈遍歷可以操作文件的所有段落。
Paragraph物件的text屬性代表該段落的文字。 from docx import Document doc = Document("./test.docx") for p in doc.paragraphs: print(p.text)

4.讀取文件表格中的文字
Document物件的tables屬性是一個包含文件所有Table物件的列表物件,
一個Table物件代表文件的一個表格。Table物件的cells屬性是一個包含表格所有_Cell物件的列表
,一個_Cell物件代表表格的一個單元格。對錶格的cells屬性進行迴圈遍歷可以操作表格的所有單元格。
_Cell物件的text屬性代表該單元格的文字。 from docx import Document doc = Document("./Python.docx") for t in doc.tables: for c in t._cells: print(c.text)

讀/寫xlsx檔案
安裝

pip install openpyxl
1.建立Excel電子表格
建立新文件需要呼叫Workbook物件的save方法,一個Workbook物件代表一個Excel工作簿,
該方法的引數是儲存的檔名。 from openpyxl import Workbook wb = Workbook() wb.save("test.xlsx")

2.建立工作表
建立工作表需要呼叫Workbook物件的create_sheet方法,該方法的引數是工作表的名稱。

from openpyxl import Workbook
wb = Workbook()
wb.create_sheet("first")
wb.create_sheet("second")
wb.save("test.xlsx")

3.修改單元格的資料
要修改表格資料,需要先呼叫load_workbook()函式開啟工作表。有三種方法從Workbook物件得到其中的一個工作表:
第一種是用Workbook物件的get_sheet_by_name方法,其引數是工作表的名稱;
第二種是用Workbook物件的worksheets屬性,該屬性是一個Worksheet物件列表,如ws = wb.worksheets[1];
第三種是通過索引的方式,下標為工作表的名字,如ws=wb['first']。

4.讀取Excel單元格中的資料
獲取一個Cell物件後,訪問Cell物件的value屬性就可讀取該單元格中的資料。

from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook("./test.xlsx")
ws = wb['first']
print(ws['A1'].value)
print(ws.cell(2, 3).value)


os模組常用方法

os.rename("wt.txt", "wtt.txt")
將當前資料夾下的檔案"wt.txt"重新命名為"wtt.txt"。

os.rename("wt.txt", ".\\tmh\\wtt.txt")
將當前資料夾下的檔案"wt.txt"複製到當前資料夾的子資料夾"tmh"中。

os.remove(".\\tmh\\wtt.txt" )
刪除當前資料夾的子資料夾"tmh"中的檔案"wtt.txt"。


os.rmdir(".\\tmh")
刪除當前資料夾的子資料夾"tmh"。

os.mkdir("d:\\tmh")
在d盤根目錄下建一個資料夾"tmh"。

os.chdir("d:\\tmh")
把"d:\\tmh"設定為當前工作目錄。

os.getcwd()
返回當前工作目錄。

listdir(path)的功能是返回path目錄下的檔案和目錄列表。對該列表進行遞迴遍歷可以遍歷資料夾path下的所有檔案和資料夾。
os.path 模組下方法

pandas屬性和方法
Series物件的常用屬性和方法

loc[ ]和iloc[ ]格式示例表

Pandas提供的資料整理方法

Pandas分組物件的屬性和方法

date_range函式的常用freq引數表


numpy的random方法和常用資料型別
NumPy 的常用資料型別

np.random 隨機數模組

matplotlib常用基礎知識
linestyle(ls)線型引數表

常用color(c)引數表

marker標記符號表

plt常用方法表

plt.legend(loc=0)用於顯示圖例,圖例的位置引數loc 

matplotlib常用圖形型別

df.plot()方法 引數

爬取三寸人間
#coding=gbk
import requests
from fake_useragent import UserAgent
from lxml import etree

url = 'https://www.81zw.com/book/32934/'
headers = {
    'User-Agent':UserAgent().random
}

response = requests.get(url,headers = headers)
e = etree.HTML(response.text)
txt_urls = e.xpath('//div[@id="list"]//@href')
txt_urls = ['https://www.81zw.com/' + txt_url[1:] for txt_url in txt_urls]

for num in range(len(txt_urls)):
    file = open('三寸人間.txt', 'a', encoding='utf-8-sig')
    response = requests.get(txt_urls[num], headers=headers)
    e = etree.HTML(response.content.decode('utf-8'))
    txt_title = e.xpath('//h1/text()')[0]
    txt_content = e.xpath('//div[@id="content"]/text()')
    file.write(str(txt_title) + '\n')
    for line in txt_content:
        file.write(line + '\n')
    # time.sleep(random.randint(1,3))
    print("第 {} 章下載完畢".format(num+1))
    file.close()

爬取圖蟲網 示例網址 https://wangxu.tuchong.com/23892889/
注:
https 和 tuchong.com 之間要有英文字元才可以進行爬取 
#coding=gbk
import requests
from fake_useragent import UserAgent
from lxml import etree
import urllib
import re
import os

pattern = 'https://(.+?)\.(.*).com'
# url = 'https://wangxu.tuchong.com/23892889/'
url = input("請輸入圖蟲網圖片地址:")
headers = {
    'User-Agent':UserAgent().chrome
}
response = requests.get(url,headers = headers)
e = etree.HTML(response.text)
img_path = '//article//img/@src'
img_urls = e.xpath(img_path)
# print(img_urls)
num = 1
for img_url in img_urls:
    response = requests.get(img_url,headers = headers)
    name = re.search(pattern,url).group(1)
    if os.path.exists("圖蟲_{}".format(name)):
        pass
    else:
        os.mkdir('圖蟲_{}'.format(name))
    urllib.request.urlretrieve(img_url, './圖蟲_{0}/圖{1}.png'.format(name,num))
    print("第{}張圖片下載完畢".format(num))
    num += 1


祝願所有努力的人,都能有所收穫!