-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathipas-python-program.py
More file actions
3362 lines (2565 loc) · 80.5 KB
/
ipas-python-program.py
File metadata and controls
3362 lines (2565 loc) · 80.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
# File : iPAS-python-program.py
# Author : Ming-Chang Lee
# Date : 2020.11.18
# YouTube : https://www.youtube.com/@alan9956
# RWEPA : http://rwepa.blogspot.tw/
# GitHub : https://github.com/rwepa
# Email : alan9956@gmail.com
Updated : 2022.01.01 -更新 08.繪圖中文字型
Updated : 2021.01.28 -新增 09.MySQL常用語法
Updated : 2021.01.28 -新增 10.Python連結MySQL
Updated : 2021.02.17 -新增 11.Python物件導向
Updated : 2021.04.11 -新增 12.iPAS 科目二:資料處理與分析概論
Updated : 2021.08.09 -新增 13.決策樹繪圖4種方法
Updated : 2021.09.30 -新增 14.深度學習CNN - MNIST範例
Updated : 2022.01.16 -新增 15.Dash視覺化簡介
Updated : 2022.02.12 -新增 16.Folium地理視覺化應用
Updated : 2022.07.02 -新增 17.Orange3簡介
Updated : 2022.08.02 -新增 18.conda虛擬環境
Updated : 2022.09.21 -新增 19.ipynb轉換為pdf檔案
Updated : 2022.11.14 -新增 20.皮馬印第安人糖尿病預測分析
Updated : 2023.02.27 -新增 21.pandas繪圖
Updated : 2023.12.17 -新增 22.顯示已經載入模組的清單
Updated : 2024.09.24 -新增 23.將 ipynb 轉換為 py 檔案
"""
# 經濟部 iPAS 巨量資料分析師認證-Python學習參考資料
# https://www.ipas.org.tw/bda/AbilityIndex.aspx
##############################
# 大綱
##############################
# 00.conda,pip操作,切換工作目錄
# 01.資料型態與基本運算
# 02.字串處理
# 03.Numpy資料結構
# 04.Pandas資料結構
# 05.流程控制與物件導向觀念
# 06.資料載入及匯出
# 07.資料變形、排序與清理
# 08.探索式資料分析(含繪圖中文字型)
# 09.MySQL常用語法
# 10.Python連結MySQL
# 11.Python物件導向
# 12.iPAS - 科目二:資料處理與分析概論
# 13.決策樹繪圖4種方法
# 14.深度學習CNN - MNIST範例
# 15.Dash視覺化簡介
# 16.Folium地理視覺化應用
# 17.Orange3簡介
# 18.conda虛擬環境
# 19.ipynb轉換為pdf檔案
# 20.皮馬印第安人糖尿病預測分析
# 21.pandas繪圖
# 22.顯示已經載入模組的清單
# 23.將 ipynb 轉換為 py 檔案
# Anaconda 下載
# https://www.anaconda.com/
##############################
# 00.conda,pip操作
##############################
# conda 資訊
conda info
# 顯示已安裝套件
conda list
pip list
# 顯示已經安裝模組的資訊
pip show pandas
# 精簡顯示已經安裝模組的版本
pip list | findstr pandas
# same as the above for Ubuntu
pip list | grep pandas
# 安裝模組
conda install 模組名稱
pip install 模組名稱
# 更新模組
conda update 模組名稱
pip install -U 模組名稱
conda update anaconda # 更新 anaconda 模組
conda update --all # 更新所有模組
# 範例: 更新 Spyder 模組
conda update spyder
# 移除模組
conda remove 模組名稱
pip uninstall 模組名稱
# 模組安裝路徑
python -m site
##############################
# 切換工作目錄
##############################
import os # 載入 os 套件
os.getcwd() # 讀取工作目錄
os.chdir("C:/pythondata") # 變更工作目錄
os.getcwd()
os.listdir(os.getcwd()) # 顯示檔案清單
# 顯示模組提供之函數
dir(os)
# jupyter notebook 清空 cache --> CTRL + Shift + R
# jupyter notebook – 更改預設目錄
"""
cd C:\
jupyter-notebook
"""
# Jupyter Notebook 行號重新計算
# Kernel / Restart & Run All
# Python程式設計-李明昌.ipynb
# http://rwepa.blogspot.com/2020/02/pythonprogramminglee.html
# Tools \ Preferences \ Keyboard shortcuts
# editor: run slection: F9 --> Ctrl + Return
# editor: run cell: Ctrl + Return --> F9
##############################
# Jupyter Notebook 轉換為 .py
##############################
# 在 Jupyter Notebook 執行以下指令, 自動建立 myjupyter_code.py
!jupyter nbconvert --to script myjupyter_code.ipynb
##############################
# 01.資料型態與基本運算.py
##############################
# 變數
# 合法
大數據 = 1 # 中文亦可,建議不要使用
CustomerSaleReport = 1
_CustomerSaleReport = 1
Customer_Sale_Report = 1
customer_sale_report = 1
# 不合法
$CustomerSaleReport = 1 # SyntaxError: invalid syntax
2020_sale = 100 # SyntaxError: invalid decimal literal
break = 123 # SyntaxError: invalid syntax
# 內建保留字
dir(__builtins__)
len(dir(__builtins__)) # 159
# 資料型態
# https://docs.python.org/3/library/stdtypes.html
# 資料型態 – 範例
# 整數 int
x1 = 1
type(x1)
# 浮點數 float
x2 = 1.234
type(x2)
# 複數 complex
x3 = 1+2j
type(x3)
# 布林值 (Boolean)
x4 = True
type(x4)
x4 + 10
# 運算子
3 + 5
3 + (5 * 4)
3 ** 2
"Hello" + "World"
1 + 1.234
7 / 2
7 // 2
7 % 2
2 ** 10
1.234e3 - 1000
x5 = 1 == 2
x5
x5 + 10
# 位移運算子: << 向左位移
# 位移運算子: >> 向右位移
a = 4 << 3 # 0100 --> 0100000, 64 32 16 8 4 2 0
b = a * 4.5
c = (a+b)/2.5
a = "Hello World"
# Tuples 序列 (元組)
f = (2,3,4,5) # A tuple of integers
# g = (,) # error code
g = ()
h = (2, [3,4], (10,11,12)) # A tuple containing mixed objects
# Tuples的操作
x = f[1] # Element access. x = 3
x
y = f[1:3] # Slices. y = (3,4)
y
z = h[1][1] # Nesting. z = 4
z
xy = (2, 3)
xy
personal = ('Hannah',14,5*12+6)
personal
singleton = ("hello",)
singleton
# Tuple Operations
("chapter",8) + ("strings","tuples","lists")
2*(3,"blind","mice")
# single format: tuple[index]
# index : 0 ~ len(tuple)-1
# index: -len(tuple) ~ -1
f= (2,3,4,5)
f[0]
f[-1] # 索引 -1 表示倒數第1個元素
f[-2]
f[len(f)-1]
# slice format: tuple [start:end ]. Items from start to (end -1)
t=((1,2), (2,"Hi"), (3,"RWEPA"), 2+3j, 6E23)
t[2]
t[:3]
t[3:]
t[-1]
t[-3:]
# Tuple Comparison Operations
# standard comparisons ‘<’, ‘<=’, ‘>’, ‘>=’, ‘==’, ‘!=’, in, not in
# Lists 串列
# 任意物件的串列
a = [2, 3, 4] # A list of integer
b = [2, 7, 3.5, "Hello"] # A mixed list
c = [] # An empty list
d = [2, [a, b]] # A list containing a list
len(d)
d[0]
d[1]
# 串列的操作
x = a[1] # Get 2nd element (0 is first)
y = b[1:3] # Return a sub-list
z = d[1][0][2] # Nested lists
b[0] = 42 # Change an element
# 串列的結合與重複
e = a + b # Join two lists
e
f = e*3 # repeat lists
f
# 附加元素
# append
a.append('BigData')
a
# extend
a.extend(['Python', 'R', "Julia"])
a
# 插入元素
a.insert(2, 999)
a
# 刪除元素
del a[4]
a
del a
print(a)
# 顯示方法
print(dir(list))
# Set 集合
# https://docs.python.org/3/tutorial/datastructures.html#sets
# 集合與字典相似, 但字典沒有key,只有值
a = set() # An empty set
type(a)
b = {"台北市", "新北市", "桃園市", "台中市", "台北市", "新北市", "高雄市"}
b # {'台中市', '台北市', '新北市', '桃園市', '高雄市'}
# 集合運算
x = {1,2,3,4,5}
y = {1,3,5,7}
x & y # {1, 3, 5}
x | y # {1, 2, 3, 4, 5, 7}
x ^ y # {2, 4, 7}
# Dictionaries 字典
a = {} # An empty dictionary
type(a) # dict
b = { 'x': 3, "y": 4 }
c = { "uid": 168,
"login": "marvelous",
"name" : 'Alan Lee'
}
# Get all keys
c.keys()
# Get an element
u = c["uid"]
# Add an element
c["shell"] = "/bin/sh"
if c.has_key("directory"): # 'dict' object has no attribute 'has_key'
d = c["directory"]
else:
d = None
if "directory" in c: # v3.x 直接使用 in
d = c["directory"]
else:
d = None
if "uid" in c: # v3.x 直接使用 in
d = c["uid"]
else:
d = None
d = c.get("directory", None) # 較簡潔
d = c.get("uid", None) # 較簡潔
##############################
# 02.字串處理
##############################
# 字串 (String)由一許多字元所組成
# 字串左右二側須使用單引號或是雙引號
# 字串物件 https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
# 字串方法 https://docs.python.org/3/library/string.html
city = '苗栗縣'
district = '造橋鄉'
road = '學府路168號'
# 使用 + 字串串接
city + district
address = city + district + road
address
# 數值轉換為字串
myinteger = 123
mystr = str(myinteger)
mystr
# len 長度
len(address)
# split 分割字串
address = city + ',' + district + ',' + road
address
address.split(',')
# replace 取代字串
address.replace(',', '')
# find 搜尋
mystr = 'Scikit-learn is an open source machine learning library that supports supervised and unsupervised learning.'
# find 回傳字串的索引, 找不到回傳-1
mystr.find('learning') # 39
mystr.find('bigdata') # -1
mystr.index('learning') # 39
mystr.index('bigdata') # ValueError: substring not found
# rfind 從最後面查詢
mystr.rfind('learning') # 98
##############################
# 03.Numpy資料結構
##############################
# NumPy 模組
import numpy as np
# 使用串列與元組建立一維陣列
a = np.array([1, 2, 3, 4, 5])
b = np.array((1, 2, 3, 4, 5))
print(type(a))
print(type(b))
print(a[0], a[1], a[2], a[3])
b[0] = 5
print(b)
b[4] = 0
print(b)
# 使用巢狀清單建立二維陣列
a = np.array([[1,2,3],[4,5,6]])
print(type(a))
print(a[0, 0], a[0, 1], a[0, 2])
print(a[1, 0], a[1, 1], a[1, 2])
a[0, 0] = 6
a[1, 2] = 1
print(a)
# 使用 save 將Numpy陣列儲存成外部檔案
outputfile = 'myarray.npy'
with open(outputfile, 'wb') as fp:
np.save(fp, a)
# 使用 load 將外部檔案匯入至Numpy陣列
outputfile = "myarray.npy"
with open(outputfile, 'rb') as fp:
mydata = np.load(fp)
print(mydata)
# 亂數函數
# 設定亂數函數的種子, 須輸入 >= 1 的整數
np.random.seed(123)
# random() 產生0.0~1.0之間的亂數
x1 = np.random.random()
x2 = np.random.random()
print(x1,x2)
# randint(min, max, size) 產生min~max之間的整數亂數, 不含max
# https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html
x3 = np.random.randint(5, 10)
x4 = np.random.randint(1, 101)
print(x3, x4)
x5 = np.random.randint(5, 21, size=3)
print(x5)
x6 = np.random.randint(1, 11, size=(4, 5))
print(x6)
# rand() 產生亂數值的陣列
a = np.random.rand(5)
print(a)
b = np.random.rand(5, 4)
print(b)
# 常數 Constants
np.NAN
# NaN and NAN are equivalent definitions of nan.
# Please use nan instead of NAN.
# 新版本使用 nan
np.nan
np.pi
np.e
a = np.array([30, 45, 60, 90])
np.sin(a*np.pi/180)
# 陣列的屬性
# reshape 應用1
a = np.array([0,1,2,3,4,5])
a
a.ndim # 1
a.shape # (6,)
# 建立副本, b之修改會影響a
b = a.reshape((3,2))
b
b.ndim # 2
b.shape # (3,2)
b[1][0] = 168
b
a # a物件已經更改, array([0, 1, 168, 3, 4, 5])
c = a.reshape((3,2)).copy()
c
c[0][0] = -999
c
a # a物件沒有更改
# reshape 應用2
a = np.array([[1, 2, 3], [4, 5, 6]])
a
b= a.reshape((3, 2))
b
b[1, 0] = 999
b
a
c = b.reshape(-1, 3)
c
# reshape 應用3
z = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
z
z.reshape(-1) # -1: unknown dimension
# array([ 1, 2, 3, ..., 10, 11, 12])
z.reshape(-1,1) # row -1: unknown , column 1
z.reshape(-1, 2) # row -1: unknown , column 2
z.reshape(1,-1) # row 1 , column: unknown
z.reshape(2, -1) # row 2 , column: unknown
z.reshape(3, -1) # row 3 , column: unknown
z.reshape(-1, -1) # ERROR
# 向量化處理
a = np.array([0,1,1,2,3,5])
a*2
a**3 # 次方運算
# indexing
a[np.array([1,3,5])]
# 離群值調整
a = a**3
a > 10
a[a > 10]
a[a > 10] = 10
a
a.clip(0, 3)
# nan 處理
x = np.array([1, 2, 3, np.NAN, 4])
x
np.isnan(x)
x[~np.isnan(x)]
np.mean(x[~np.isnan(x)])
np.mean(x) # nan
# 計算時間
import timeit
import numpy as np
normal_py_sec = timeit.timeit('sum(x*x for x in range(1000))', number=10000)
naive_np_sec = timeit.timeit('sum(na*na)', setup="import numpy as np; na=np.arange(1000)", number=10000)
good_np_sec = timeit.timeit('na.dot(na)', setup="import numpy as np; na=np.arange(1000)", number=10000)
print("Normal Python: %f sec"%normal_py_sec)
print("Naive NumPy: %f sec"%naive_np_sec)
print("Good NumPy: %f sec"%good_np_sec)
print "Hello World" # python 2, Python 3 with ERROR
print("Hello World") # python 3
# np.argmax 運算
# 一維向量
x = np.arange(12)
x # array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
print(x.ndim) # 1
print(x.shape) # (12,)
print(np.argmax(x)) # 11
# 二維向量, axis=0 依行為操作, 找出各行最大值的指標
x = np.array([[1,2,5,6],
[18,7,6,5],
[9,12,7,2]])
# array([[ 1, 2, 5, 6],
# [18, 7, 6, 5],
# [ 9, 12, 7, 2]])
print(np.argmax(x, axis=0)) # [1 2 2 0]
# 二維向量, axis=1 依列為操作
print(np.argmax(x, axis=1)) # [3 0 1]
# 二維向量, axis=-1
print(np.argmax(x, axis=-1)) # [3 0 1]
# 二維向量, axis=-2
print(np.argmax(x, axis=-2)) # [1 2 2 0]
##############################
# 04.Pandas資料結構
##############################
# pandas 設定顯示所有欄位
pd.set_option('display.expand_frame_repr', False)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
# 載入2大套件 pandas, numpy
# https://pandas.pydata.org/docs/user_guide/10min.html
import pandas as pd # Python Data Analysis Library
import numpy as np # Python Scientific Computing Library
# 序列(Series)物件
# 使用串列(List)建立序列物件
# 序列包括指標(Index) 與值(Value), 指標採用預設整數型態指標
s = pd.Series([1,3,5,np.nan,6,8])
s
type(s)
# 使用陣列(array)建立資料框(DataFrame)
dates = pd.date_range('20200801', periods=6) # 日期指標
dates
type(dates)
# 方法1 使用串列 (list) 建立 pandas DataFrame
# 建立 list
data = ['Alan', 'Lee', 'RWEPA']
# 建立 pandas DataFrame
df = pd.DataFrame(data, columns=['Name'])
# 列印 dataframe
df
# Out:
# Name
# 0 Alan
# 1 Lee
# 2 RWEPA
# 方法2 使用串列的串列 (lists of lists) 建立 pandas DataFrame
# 建立 list
data = [['Alan', 2000], ['Lee', 2020], ['RWEPA', 2013]]
# 建立 pandas DataFrame
df = pd.DataFrame(data, columns=['Name', 'Year'])
# 列印 dataframe
df
# Out:
# Name Year
# 0 Alan 2000
# 1 Lee 2020
# 2 RWEPA 2013
# 方法3 使用narray(串列)的字典 (dict of narray/lists) 建立 pandas DataFrame
# 建立 dict of list
data = {'Name': ['Alan', 'Lee', 'RWEPA', 'Python'], 'Age': [2000, 2020, 2013, 1991]}
# 建立 pandas DataFrame
df = pd.DataFrame(data)
# 列印 dataframe
df
# Out:
# Name Age
# 0 Alan 2000
# 1 Lee 2020
# 2 RWEPA 2013
# 3 Python 1991
# 方法4 使用 字典的串列 (list of dicts) 建立 pandas DataFrame
# 建立 dict of list
data = [{'Name': 'Alan', 'Age': 2000},
{'Name': 'Lee', 'Age': 2020},
{'Name': 'RWEPA', 'Age': 2013},
{'Name': 'Python', 'Age': 1991}]
# 建立 pandas DataFrame
df = pd.DataFrame(data)
# 列印 dataframe
df
# Out:
# Name Age
# 0 Alan 2000
# 1 Lee 2020
# 2 RWEPA 2013
# 3 Python 1991
# 方法5 使用明確索引指標並建立 pandas DataFrame
# 建立 dict of list
data = {'Name': ['Alan', 'Lee', 'RWEPA', 'Python'],
'Age': [2000, 2020, 2013, 1980]}
# 建立 pandas DataFrame
df = pd.DataFrame(data,
index=['id1', 'id2', 'id3', 'id4'])
# 列印 dataframe
df
# Out:
# Name Age
# id1 Alan 2000
# id2 Lee 2020
# id3 RWEPA 2013
# id4 Python 1980
# 範例: 資料框(DataFrame)物件
# 欄位名稱: A, B, C, D
df1 = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
df1
type(df1)
# 使用字典建立資料框 DataFrame
df2 = pd.DataFrame({ 'A' : 1.,
'B' : pd.Timestamp('20190101'),
'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
'D' : np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo' })
df2
# dtypes: 表示資料型態
df2.dtypes # df2. 按 [Tab] 按鈕
# Viewing Data 資料檢視
df1
# head 顯示前 5 筆資料, 此功能與 R 顯示 6 筆不相同.
df1.head()
df1.head(3)
df1.tail()
# 顯示指標(index)
df1.index
# 欄名稱(columns)
df1.columns
# 資料值(values)
df1.values
# describe 統計摘要(statistic summary)
# count 個數
# mean 平均值
# std 標準差 standard deviation, 一般希望愈小愈好
# min 最小值
# 25% 25百分位數
# 50% 50百分位數, 中位數 median
# 75% 75百分位數 (quantile)
# max 最大值
df1.describe()
# 排序 sort_values()
# axis為排序的軸,0表示 rows index(列指標),1表示columns index(行指標)
# 當對數據 "列" 進行排序時,axis必須設置為0.
# df.sort(["A"]) 新版不支援 sort, 改用 sort_values 或 sort_index
# ascending =FALSE, 即遞增是FALSE, 表示遞減是TRUE, 結果為D,C,B,A
df1.sort_index(axis=1, ascending=False)
# 依照 B 欄大小, 由小至大排序
df1.sort_values(by='B')
# 選取行
df1['A']
df1.A
# 選取列, 此功能與 R 不同, R: df[1:4] 表示選取第1至第4行
df1
df1[1:4]
# 使用 loc
df1.loc[:, ['A','B']]
# 使用 iloc
df1.iloc[2] # 指標為第2列
df1.iloc[2:4,]
df1.iloc[2:4, :]
df1.iloc[, 2] # ERROR
df1.iloc[:, 2] # OK
df1.iloc[:, 2:4]
# 取出一個儲存格 cell, 使用 at 或 iat
# at 使用變數名稱
df2.at[0,'A']
# iat 使用指標 index
df2.iat[1,4]
# Boolean Indexing 邏輯值(條件式)資料選取
df1[df1 > 0]
df1[df1.A > 0]
# 使用 .isin
df1[df1.index.isin(['2020-08-02', '2020-08-04'])]
# 建立資料框
df2 = df1.reindex(index=dates[0:4], columns=list(df1.columns) + ['E'])
df2
# Missing Data 遺漏值 NaN, R: 使用NA
df2.loc[dates[0]:dates[1],'E'] = 1
df2
# 刪除列中包括 NaN
df2.dropna(how='any')
# 將遺漏值填入值
df2.fillna(value=999)
# 判斷何者為NaN
pd.isnull(df2)
# 計算每行平均
df2.mean()
# 計算每列平均
df2.mean(1)
# Apply 將資料套用至函數
df2.apply(np.cumsum)
# Merge 合併
df = pd.DataFrame(np.random.randn(10, 4))
df
pieces = [df[:3], df[4:7], df[8:]]
pieces
# 列合併, 類似 R的 rbind
pd.concat(pieces)
# Grouping 群組計算
import numpy as np
np.random.seed(168)
df = pd.DataFrame({
'A' : [np.nan, 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
df
# Out:
# A B C D
# 0 NaN one 0.528954 1.460272
# 1 bar one 2.481557 -0.569446
# 2 foo two -0.770050 -1.532260
# 3 bar three -1.199675 2.365692
# 4 foo two 0.423453 -0.275542
# 5 bar two 0.968783 1.387176
# 6 foo one 0.087928 -0.608194
# 7 foo three 1.741998 -1.231810
df['A'].value_counts() # 預設為刪除 NaN 次數, 類似 R: table函數
# Out:
# foo 4
# bar 3
# Name: A, dtype: int64
df['A'].value_counts(dropna=False) # 加上 NaN 次數
# Out:
# foo 4
# bar 3
# NaN 1
# Name: A, dtype: int64
df.groupby('A').sum() # 類似 R- aggregate
# Out:
# C D
# A
# bar 2.250665 3.183422
# foo 1.483329 -3.647806
df.groupby(['A','B']).sum()
# Out:
# C D
# A B
# bar one 2.481557 -0.569446
# three -1.199675 2.365692
# two 0.968783 1.387176
# foo one 0.087928 -0.608194
# three 1.741998 -1.231810
# two -0.346598 -1.807802
# 繪圖
ts = pd.Series(np.random.randn(1000),
index=pd.date_range('1/1/2000', periods=1000))
ts
ts = ts.cumsum()
ts.plot()
##############################
# 05.流程控制與物件導向觀念
##############################
# elif敘述
a = '+'
if a == '+':
op = 'PLUS'
elif a == '-':
op = 'MINUS'
else:
op = 'UNKNOWN'
op
# 沒有像C語言一樣,有switch的語法
# 布林表示式 – and, or, not
a = 1
b = 6
c = 9
if b >= a and b <= c:
print('b is between a and c')
if not (b < a or c > c):
print('b is still between a and c')
#================
# Functions 函數
#================
# Return the remainder of a/b
def remainder(a,b):
q = a/b
r = a - q*b
return r
# Now use it
a = remainder(42,5) # a = 2
# Return two values
def divide(a,b):
q = a/b
r = a - q*b
return q,r
x,y = divide(42,5) # x = 8, y = 2
# 檔案處理
# 1.檔案的讀取/寫入
f = open("foo","w") # Open a file for writing
f.write("Hello World")
f.close()
g = open("foo","r") # Open a file for reading
data = g.read() # Read all data
data
g = open("foo","r")
line = g.readline() # Read a single line
line