Case Study: Colaboratory

ไพธอน คือ

Python

  • ภาษาโปรแกรมเชิงวัตถุสำหรับใช้งานหลายด้าน

  • รองรับหลายระบบปฏิบัติการ

  • เขียนง่าย อ่านง่าย

  • มีชุดคำสั่งเสริมมากมาย สำหรับหลากหลายด้าน

ทำไมไพธอนมีคนใช้เยอะ?

  1. เป็นภาษาโปรแกรมที่นิยมใช้ในการพัฒนาซอฟตแวร์

  1. เป็นภาษาโปรแกรมที่นิยมใช้ในงานด้านวิทยาการข้อมูล

  1. เป็นภาษาโปรแกรมที่ได้รับความนิยมในการพัฒนาระบบ IoT

คำสั่งพื้นฐาน

  1. คำสั่งแสดงข้อความ

print('สวัสดี')
  1. คำสั่งรับข้อความจากผู้ใช้

input()
  1. คำสั่งนำเข้าข้อมูลและใช้ตัวแปร x อ้างอิง

ข้อมูลที่นำเข้าเป็นข้อความ str

x = input()

ตัวแปร

ชื่อที่ใช้อ้างอิงข้อมูลในระบบ

สายอักขระที่ประกอบด้วย a-z, A-Z, 0-9, _, แต่ตัวแรกต้องไม่เป็น 0-9

ตัวอย่างชื่อต่อไปนี้สามารถใช้เป็นชื่อของตัวแปรได

i
x
y
name
u

ข้อมูล

ตัวแปรเอาไว้ใช้อ้างอิงถึงข้อมูล ซึ่งประเภทของข้อมูลแบ่งออกเป็น 2 ประเภทใหญ่ ๆ ได้แก่

  1. ข้อมูลพื้นฐาน

  2. ชุดข้อมูล

1. ข้อมูลพื้นฐาน

  1. ข้อมูลตัวเลข

    • ข้อมูลจำนวนเต็ม เช่น 3  7   0    -1

    • ข้อมูลเลขทศนิยม เช่น 3.0   0.555   -1E3

  2. ข้อมูลตรรกะ

    • True

    • False

2. ชุดข้อมูล

  1. ชุดข้อมูลมีลำดับ

str, tuple, list

สมาชิกในชุดข้อมูลมีลำดับ(ตำแหน่ง) แน่นอน

'อลิษา จิตใจมั่น'
"มงคล มิ่งขวัญ"

(1, 2, 3, 4)
(15.1221388, 104.909696)  # lat,lng ของหนองอีแจม

[ 'มานี', 'มานะ', 'ชูใจ', 'พอใจ', "ปิติ" ]
[10, 9, 8, 6, 7, 3, 2]

ชุดข้อมูลเหล่านี้ช่วยให้เราเข้าถึงสมาชิกได้โดยใช้ตัวเลขจำนวนเต็มระบุตำแหน่ง เริ่มจากตำแหน่งที่ 0 เป็นสมาชิกตัวแรกของชุดข้อมูล

  1. ชุดข้อมูลแบบไม่มีลำดับ

non-sequence data type

set, dict

สมาชิกในชุดข้อมูลไม่มีลำดับที่แน่นอนไม่สามารถเข้าถึงสมาชิกโดยใช้ลำดับได้

{ 'A', 'B', 'C', 'D' }
{ 1, 3, 4, 9, 5 }

{ 'มานี': 3.44,  'มานะ': 3.99, 'ชูใจ': 3.24}

สำหรับ dict การเข้าถึงสมาชิกทำได้โดยการระบุ key ของสมาชิกแทน

std = { 'มานี': 3.44,  'มานะ': 3.99, 'ชูใจ': 3.24}

std['มานี'] = 3.55

avggpa = (std['มานี'] + std['มานะ'] + std['ชูใจ'])/len(std)

ชุดคำสั่งเสริม (Module)

  • regular import - คำสั่งนำเข้าชุดคำสั่งเสริม

import math
x = math.pi
math.cos(x)

import requests
  • function import - คำสั่งนำเข้าเฉพาะฟังก์ชัน

from math import pi, cos
cos(pi)

from IPython.display import Image
  • rename import - คำสั่งนำเข้าพร้อมเปลี่ยนชื่อ

import math as m
m.cos(m.pi)

import matplotlib.pyplot as plt

แบบฝึกหัดโปรแกรมแสดงภาพ

ตัวแปรและชุดคำสั่งเสริม

  1. คำสั่งสร้างตัวแปร w มีค่าเป็น 800 เพื่อเป็นความกว้างของภาพ

w = 800
  1. คำสั่งสร้างตัวแปร h มีค่าเป็น 600 เพื่อเป็นความสูงของภาพ

h = 600
  1. คำสั่งสร้างตัวแปร url มีค่าเป็นข้อความ https://source.unsplash.com/random/

url = 'https://source.unsplash.com/random/'
  1. คำสั่งสร้างตัวแปร imgurl มีค่าเป็นข้อความ https://source.unsplash.com/random/800x600

imgurl = 'https://source.unsplash.com/random/800x600'
  1. คำสั่งสร้างตัวแปร imgurl ที่มีค่าเหมือนกับข้อ 4 แต่ใช้ค่าจาก w และ h

imgurl = f'https://source.unsplash.com/random/{w}x{h}'
  1. คำสั่งนำเข้า Image จากชุดคำสั่งเสริม IPython.display

from IPython.display import Image
  1. คำสั่งสร้าง Image เพื่อแสดงรูปจาก imgurl

Image(url=imgurl)
Image(url=imgurl)

คำสั่งแปลงข้อความเป็นตัวเลข

  1. คำสั่งแปลงข้อความจากผู้ใช้เป็นจำนวนเต็ม

a = input()
x = int(a)
  1. คำสั่งแปลงข้อความจากผู้ใช้เป็นจำนวนเต็ม

a = input()
y = float(a)

ตัวดำเนินการทางคณิตศาสตร์

x =   5 + 9     # บวก
y =   9 - 4     # ลบ
z =   x * y     # คูณ
z =   9 / 2     # หาร
z =   x ** 2.5  # ยกกำลัง
z = 100 % y     # mod (เศษที่ได้จากการหาร)

ตัวดำเนินการผสมสำหรับกำหนดค่า

x +=   5       #  x = x + 5
y -=   9       #  y = y - 9
z *=   x       #  z = z * x
z /=   9       #  z = z / 9
z **=  x       #  z = z ** x
z %=   y       #  z = z % y

แบบฝึกหัดคำนวณทางคณิตศาสตร์

จงเขียนคำสั่งเพื่อคำนวณหาค่าของ \(x, y, z\)

\[\begin{split}r = 23 \\ x = 2\pi r \\ y = \pi r^2 \\ z = \sqrt{x^2 + y^2} \\\end{split}\]
r = 23
from math import pi
x = 2*pi*r
y = pi*r**2
from math import sqrt
z = sqrt(x**2 + y**2)

เครื่องหมายเปรียบเทียบ

เครื่องหมาย

ความหมาย

<

น้อยกว่า

>

มากกว่า

<=

น้อยกว่าหรือเท่ากับ

>=

มากกว่าหรือเท่ากับ

==

เท่ากับ

!=

ไม่เท่ากับ

เครื่องหมายทางตรรกะ

  • Logical

2 < x and x < 10     #  &&
2 < x or  x > 10     #  ||
2 < x < 10
  • เพิ่มเติม

a = [2,4,6,8]
2 in a
1 not in a
len(a) is 4

คำสั่งเลือกทำงาน (Selection)

if

if gpa > 3.5:
  print('เกียรตินิยมอันดับหนึ่ง')

if-elif

if gpa > 3.5:
  print('เกียรตินิยมอันดับหนึ่ง')
elif gpa > 3.25:
  print('เกียรตินิยมอันดับสอง')
else:
  print('เกรดเฉลี่ยสูง')

if-else

  • regular if-else

if 1 in a:
    print('a contains 1.')
else:
    print("a doesn't contains 1")
  • one-liner

print('a contains 1.' if 1 in a else "a doesn't contains 1.")

คำสั่งทำซ้ำ (Loop)

while

while เงื่อนไข:
    statements
  • ตัวอย่าง

x = 1
y = 10
while x != y:
    x += 1
    y -= 1

for

a = [1, 2, 3, 4, 5, 6]
for x in a:
    print(x**2)

for i in range(10):
    print(i)

for i in range(1,10,2):
    print(i)

ฟังก์ชันพื้นฐาน

abs(-10.0)                  # ค่าสัมบูรณ์
max( [1,3,2,4,5] )          # ค่าสูงสุดใน list
min( [2,3,9,7,10,12] )      # ค่าต่ำสุดใน list
round(12345.12345, 3)       # ปรับให้เหลือ 3 ตำแหน่ง
cmp(a, b)                   # a<b = -1, a==b = 0, a>b == 1
eval('20.932')              # แปลงข้อความเป็นตัวเลข
type(a)                     # ดูชนิดข้อมูลของตัวแปร a
range(start,stop,step)

แบบฝึกหัดกราฟ

การสร้างและใช้งานลิสต์ คำสั่งทำซ้ำ ฟังก์ชัน

  1. คำสั่งสร้างตัวแปร x เป็นลิสต์

x = []
  1. คำสั่งสร้างตัวแปร x เป็นลำดับ(ลิสต์)ของตัวเลข -10 ถึง 10 โดยใช้ range()

x = list(range(-10,10))
x = list(range(-10, 10))
  1. คำสั่งสร้างตัวแปร x ที่เป็นลำดับ(ลิสต์)ของตัวเลข -10 ถึง 10 โดยมีช่วงห่าง 0.1

n = -10
x = []
while n < 10:
  x.append(n)
  #n += ???
n = -10
x = []
while n < 10.1:
  x.append(n)
  n += 0.1
  1. คำสั่งสร้างตัวแปร y ที่มีค่าเป็น \(y=0.5x^2-2x\)

y = []
for i in x:
  y.append(x*x)
y = []
for i in x:
  y.append(0.5*i**2 - 2*i)
  1. คำสั่งนำเข้าชุดคำสั่งเสริมเพื่อแสดงกราฟ

import matplotlib.pyplot as plt

plt.plot(x,y)
import matplotlib.pyplot as plt
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x7fd08b869df0>]
../_images/output_72_1.png

ฟังก์ชันอ่านเขียนไฟล์

  • เปิดไฟล์เพื่ออ่านข้อความในไฟล์

f = open('file.txt', 'r')
lines = f.readlines()
f.close()
print(lines)
with open('file.txt', 'r') as f:
    lines = f.readlines()
    print(lines)
  • เปิดไฟล์เพื่อเขียนข้อความ

f = open('file.txt', 'w')
f.write('text in line one\n')
f.writelines(['text in line two\n', 'line 3\n', 'line 4\n'])
f.close()
with open('file.txt', 'w') as f:
    f.write('text in line one\n')
    f.writelines(['text in line two\n', 'line 3\n', 'line 4\n'])

การเขียนฟังก์ชัน

  • การประกาศฟังก์ชัน

def timestable(x):
    for i in range(1,13):
        print('{}x{}={}'.format(i,x,i*x))
  • การเรียกใช้ฟังก์ชัน

timestable(9)

แบบฝึกหัดโปรแกรมแสดงภาพ

แบบฟังก์ชัน

  1. สร้างฟังก์ชันชื่อ show_image(w, h)

def show_image(w, h):
  1. แปลง w และ h เป็น imgurl

def show_image(w, h):
  imgurl = f'https://source.unsplash.com/random/{w}x{h}'
  return Image(url=imgurl)
  1. ทดสอบเรียกใช้ฟังก์ชัน show_image(800,600)

แบบฝึกหัดแผนที่ผู้ป่วยโควิด 19

requirements:

!pip install requests pandas oauth2client gspread google-colab

นำเข้าข้อมูลจากกรมควบคุมโรค

https://covid19.ddc.moph.go.th

  1. นำเข้าชุดคำสั่ง requests

  2. ร้องขอข้อมูลรายงานจำนวนผู้ป่วย Covid-19 รายจังหวัดของกรมควบคุมโรค

url = 'https://covid19.ddc.moph.go.th/api/Cases/today-cases-by-provinces'
response = requests.get(url)
covid_data = response.json()
# print( covid_data[:5] )
covid_by_provinces = {}
for d in covid_data:
  covid_by_provinces[d['province']] = d

นำเข้าข้อมูลละติจูด ลองติจูดของจังหวัดต่างๆ

(a). นำเข้าข้อมูลจาก Google Spread Sheet ผ่าน Google Colaboratory

https://docs.google.com/spreadsheets/d/1B1jGyQjiVlC-2Gf1ga8SVFrJhkLTz5eWeF2t_tKub0k/edit?usp=sharing

from google.colab import auth
auth.authenticate_user()
url = 'https://docs.google.com/spreadsheets/d/1B1jGyQjiVlC-2Gf1ga8SVFrJhkLTz5eWeF2t_tKub0k/edit?usp=sharing'
import gspread
from oauth2client.client import GoogleCredentials
gc = gspread.authorize(GoogleCredentials.get_application_default())
wb = gc.open_by_url(url)
ws = wb.get_worksheet(0)
province_data = ws.get_all_records()
print( province_data[0] )

(b). นำเข้าข้อมูลจาก json

https://wichit2s.gitlab.io/python/_static/data/Thailand-Provinces.json

url = 'https://wichit2s.gitlab.io/python/_static/data/Thailand-Provinces.json'
province_data = requests.get(url).json()
print(province_data[:3])

จัดเก็บข้อมูลให้เหมาะสม

provinces = {}
for d in province_data:
  name = d['PROVINCE']
  provinces[name] = {
      'name': name,
      'image': d['IMAGE'],
      'region': d['COUNTY'],
      'latlng': [ d['LATITUDE'], d['LONGITUDE'] ],
      'new_case': covid_by_provinces[name]['new_case'],
      'total_case': covid_by_provinces[name]['total_case'],
  }
print( provinces['อุบลราชธานี'] )

นำเข้าชุดคำสั่งเสริม folium

import folium
map_center = provinces['กรุงเทพมหานคร']
m = folium.Map(location=map_center['latlng'])

สร้าง Marker จากข้อมูลทุกจังหวัด

for name,p in provinces.items():
  popup_html = f"""
   <div
   style="box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  transition: 0.3s;
  border-radius: 5px;">
    <img src="{p['image']}" alt="Avatar"
    style="border-radius: 5px 5px 0 0;width:100%">
    <div style="padding: 2px 16px;">
      <h4><b>ผู้ป่วยรายใหม่ {p['new_case']:,} ราย</b></h4>
     <p>{name}</p>
    </div>
  </div>
    """
  iframe = folium.IFrame(html=popup_html, width=220, height=350)
  marker = folium.Marker(
    p['latlng'], popup=folium.Popup(iframe), tooltip=f"{name} {p['new_case']} คน"
  )
  marker.add_to(m)

แสดงแผนที่อีกครั้ง

m
Make this Notebook Trusted to load map: File -> Trust Notebook