สรุปประเภทการจัดเก็บของข้อมูลในภาษา python data-types-for-data-science-in-python

Image placeholder
แวะมาทักทายกันได้


สรุปประเภทการจัดเก็บของข้อมูลในภาษา python ตอนที่ 1 

1️⃣ ในหลายๆ ภาษาที่ใช้เขียนโปรแกรมในปัจจุบัน แม้ว่าจะเริ่มหันมาใช้การไม่กำหนดตัวแปร หรือใช้ ตัวแปรแบบใดก็ได้ (any type variable) กันมากขึ้น เพราะเพื่อความสะดวกโดยให้โปรแกรมภาษาจัดการตัวแปรให้อัตโนมัติ แต่อย่างไรก็ตาม ก็จำเป็นต้องเข้าใจชนิดในการจัดเก็บตัวแปร เพื่อเข้าใจลักษณะวิธีการเรียกใช้ ให้เหมาะสมกับการทำงานโปรแกรมของเรา

2️⃣ สำหรับตอนใหม่ series บทความนี้จะเขียนถึงภาษา python ที่ใช้ในงานเขียนโปรแกรมต่างๆ ทางด้าน data science และ data engineer แต่อย่างไรก็ตามก็ไปประยุกต์ในกับงาน web service หรือ web application ได้ โดยจะเริ่มตอนนี้เป็นตอนแรก และ อยู่ในระดับ basic level จนถึง intermediete level บางจุดคำศัพท์ต่างๆ อาจจะ geek มือใหม่อาจจะต้องค้นคว้าเพิ่มเติม หรือ comment ถามเอาไว้ ถ้าผู้เขียนสามารถที่จะแวะเขียนเรื่องที่ถามได้ ก็จะเขียนเข้าไปด้วย ฝากติดตามกันไว้ด้วยนะครับ #เรียนไปด้วยกัน

3️⃣ ในการจัดการข้อมูลต่างๆ เราใช้การเขียนโปรแกรมเข้ามาช่วยให้เกิดความสะดวกสบายมากขึ้น โดยเฉพาะการทำงานซ้ำๆ พิมพ์ข้อความซ้ำๆ การตัดคำซ้ำๆ การต่อคำซ้ำๆ การทำอะไรซ้ำๆ โดยที่มนุษย์ขี้เกียจอย่างเราก็ต้องหาเครื่องมือมาช่วยให้ชีวิตของเราไม่มาวุ่นวาย ก็การเขียนโปรแกรมนี้แหละ โดยเฉพาะเรื่องของการจำ บางอย่างสมองของมนุษย์ ไม่สามารถจำอะไรได้ทั้งหมด ต้องใช้การจดบันทึกมาช่วยในการจำ คอมพิวเตอร์ก็มีส่วนที่ต้องใช้ ความจำ เช่นเดียวกัน

4️⃣ แต่บทความนี้ ไม่ลงลึกไปเรื่อง hardware เราจะเล่นกับงานที่มัน abstract ต้องใช้จินตนาการ และ สมมติมันขึ้นมาว่า มันคือ กล่องสำหรับเก็บข้อมูลต่างๆ (container) ให้กับเรา

5️⃣ ชนิดของกล่องเก็บข้อมูล (container) ในภาษา python มีหลายชนิด สำหรับตอนที่ 1 นี้จะเขียนเฉพาะ List, Tuple, และ String




  • ——————— *

  • 1️⃣0️⃣0️⃣ หากใครไม่อยากพลาด *

  • โพสต์เรื่องเกี่ยวกับ *

  • data analyst, data science, *

  • data engineer และ programming *

  • ในโพสต์ถัดๆไป ฝากแชร์ *

  • กดติดตาม profile กันไว้ด้วยนะครับ *

  • *——————— **

6️⃣ ขอเรียกสั้นๆว่า container คุณสมบัติต่างๆที่ใช้ในการเก็บข้อมูล มีดังต่อไปนี้

  • จัดเก็บข้อมูลตามลำดับ (index)
  • จัดเก็บข้อมูลสำหรับคำนวน (aggregation)
  • สามารถเรียงลำดับ (sort)
  • สามารถค้นหาข้อมูล (search)

7️⃣ นอกจากนี้ สามารถ จัดการข้อมูลต่างๆ ใน container ได้อีกเช่น

  • เพิ่มและลบสมาชิก (element)
  • container บางชนิดไม่สามารถแก้ไขข้อมูลในสมาชิก (element) ได้
  • การแทนที่ (replace) ข้อมูลในลำดับของสมาชิก

8️⃣ และการวนซ้ำ (loop) หรือ iterable จะเหมาะกับการทำงานบางอย่างเช่น

  • การจัดกลุ่ม
  • การรวมข้อมูล
  • การคำนวนต่างๆ

มาพบกับ container ชนิดแรกกัน

9️⃣ List

เรามักจะเจอข้อมูลประเภทนี้อยู่บ่อยๆ ในภาษาอื่นๆ จะเรียก List ว่า Array โดยมีคุณสมบัติในการเก็บข้อมูลได้หลายชนิด เช่นmy_list = [1, 'apple', 3.14, True] ซึ่ง ตามตัวอย่างก็จะมี Integer, String, Float, Boolean แม้กระทั่ง List ก็สามารถเก็บเพิ่มได้

1️⃣0️⃣  List สามารถแก้ไขข้อมูลในแต่ละ element ได้ เช่น

  • การเพิ่ม (Append) สมาชิกใน List
  • การเข้าถึงสมาชิกแต่ละตัว (access single item in list)
  • การรวม List ที่มี 2 List (combining lists)
  • การค้นหาสมาชิก (finding element in a list)
  • การลบ (Remove) สมาชิกใน List
  • การวนลูป (Iterable) ใน List
  • การจัดเรียง (sort) ใน List

ให้จำตัวแปรนี้ไว้ว่า มีการเก็บข้อมูลแบบนี้

cookies = ['chocolate chip', 'peanut butter', 'sugar']

1️⃣1️⃣ การเพิ่ม (Append) สมาชิกใน List

cookies = ['chocolate chip', 'peanut butter', 'sugar']
cookies.append('Triggel')

print(cookies)

# ['chocolate chip', 'peanut butter', 'sugar', 'Triggel']

1️⃣2️⃣ การเข้าถึงสมาชิกแต่ละตัว (access single item in list)

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

cookies = ['chocolate chip', 'peanut butter', 'sugar']
print(cookies[1])

# peanut butter

1️⃣3️⃣ การรวม List ที่มี 2 List (combining lists)

มีตัวแปร list อยู่ 2 ตัว คือ cookies กับ cake นำมา merge กัน

cookies = ['chocolate chip', 'peanut butter', 'sugar']
cake = ['strawberry', 'vanilla']

deserts = cookies + cake

print(desserts)

# ['chocolate chip', 'peanut butter', 'sugar', 'strawberry', 'vanilla']

1️⃣4️⃣ หรือสามารถ รวมด้วย method extend() ก็ได้ เช่น

cookies.extend(cake)

# ['chocolate chip', 'peanut butter', 'sugar', 'strawberry', 'vanilla']

1️⃣5️⃣ การค้นหาสมาชิก (finding element in a list) ใช้ method .index()

position = cookies.index('sugar')
print(position)

# 3

1️⃣6️⃣ การลบ (Remove) สมาชิกใน List ใช้ method .pop()

name = cookies.pop(position)

print(name)

# sugar

print(cookies)

# ['chocolate chip', 'peanut butter']

1️⃣7️⃣ การวนลูป (Iterable) ใน List

ในการ loop ใน list เราสามารถใช้ List Comprehensions ที่สามารถเขียน Loop ในบรรทัดเดียว เพื่อ action หรือ คำนวนค่าบางอย่างที่อยู่ใน list เช่น ทำให้ตัวหน้าเป็นตัวใหญ่

titlecase_cookies = [cookie.title() for cookie in cookies]
print(titlecase_cookies)

# Chocolate Chip
# Peanut butter 
# Sugar

1️⃣8️⃣ การจัดเรียง (sort) ใน List ใช้ method sorted()

cookies = ['chocolate chip', 'peanut butter', 'Triggel']

sorted_cookies = sorted(cookies)
print(sorted_cookies)

# ['Triggel', 'chocolate chip', 'peanut butter']

1️⃣9️⃣ ทูเพิล (tuple)

Tuple คล้ายกับ List ซึ่งมีการเก็บข้อมูลตามลำดับเช่นเดียวกัน สามารถเข้าถึงสมาชิกภายใน Tuple ด้วย Index แต่ส่วนที่ต่างจะมีดังนี้

  • Tuple สามารถประมวลผลและมีหน่วยความจำมากกว่า List
  • Tuple เป็นประเภทการจัดเก็บข้อมูลที่ไม่สามารถเปลี่ยนแปลงได้ (immutable) ก็คือ ไม่สามารถ เพิ่ม หรือ ลบ สมาชิกภายใน Tuple ได้
  • Tuple สามารถจับคู่ข้อมูลกันได้ (Pair)
  • การแยก Tuple ที่จับคู่เอาไว้ออกจากกัน (Unpacking)

2️⃣0️⃣ Tuple สามารถจับคู่ข้อมูลกันได้ (Pair)

บ่อยครั้ง เราจะมีการจับคู่สมาชิกของ List 2 ตัว โดยจะใช้ฟังก์ชัน zip ในการ merge กัน เช่น

ยกตัวอย่าง List us_cookies และ in_cookies

us_cookies = ['Chocolate Chip', 'Brownies', 'Peanut Butter']
in_cookies = ['Punjabi', 'Fruit Cake Rusk', 'Marble Cookies']

top_pairs = list(zip(us_cookies, in_cookies))

#[('Chocolate Chip', 'Punjabi'), ('Brownies', 'Fruit Cake Rusk'), ('Peanut Butter', 'Marble Cookies') ]

2️⃣1️⃣ การแยก Tuple ที่จับคู่เอาไว้ออกจากกัน (Unpacking)

us_num_1, in_num_1 = top_pairs[0]
print(us_num_1)
# Chocolate Chip

print(in_num_1)
# Punjabi

2️⃣2️⃣ ถ้าทำทีละตัวคงจะลำบาก ก็ส่งเข้า loop

for us_cookie, in_cookie in top_pairs:
	print(in_cookie)
	print(us_cookie)

2️⃣3️⃣ สตริง (String)

สตริงเป็นประเภทของลำดับเช่นเดียวกัน (sequence) เป็นประเภทที่พบบ่อยที่สุด สามารถที่จะวนลูปผ่านสตริงได้เหมือนกับประเภทอื่น ๆ

2️⃣4️⃣ ในการกำหนด String ใน Python สามารถใช้ตัวอักษร ‘f’ นำหน้าข้อความเพื่อบอกว่านี้คือชุดข้อความนะ แล้วภายในชุด String สามารถเข้าถึงข้อมูลในตัวแปรอื่นๆได้ ด้วยใส่เอาไว้ในวงเล็กปีกกา เช่น

# Creating a formatted string
cookie_name = "Anzac"
cookie_price = 1.99

print(f"Each {cookie_name} cookie costs {cookie_price}")

# Each Chocolate Chip cookie costs 1.99

2️⃣5️⃣ โดยคุณสมบัติ ต่างของ string เช่น

  • การรวม string
  • การค้นหา string
  • การจัดการกับ case insensitive

2️⃣6️⃣ การรวม string โดยใช้ method join

# Joining a string with a list
child_ages = ["3", "4", "7", "8"]

print(", ".join(child_ages))

# "3, 4, 7, 8"

2️⃣7️⃣ การค้นหา string โดยใช้ method startswith() สามารถใช้ค้นหาสตริงที่ขึ้นต้นหรือลงท้ายด้วยตัวอักษร ได้เช่น ตัวอย่าง ค้นหาด้วยตัวอักษร A

boy_names = ["Mohamed", "Youssef", "Ahmed"]

print([name for name in boy_names if name.startswith("A")])

# ["Ahmed"]

2️⃣8️⃣ นอกจากนี้ การค้นหา string สามารถใช้คำสั่ง in ได้ด้วยเช่น


quote = "Life is a long lesson in humility." print("long" in quote) print("life" in quote) # True False

2️⃣9️⃣ การจัดการกับ case-sensitive คือการใช้เมธอด lower() บนสตริง

# Being case insensitive
print("life" in quote.lower())

#
True


1️⃣0️⃣0️⃣ โดยสรุป ประเภทของการจัดเก็บข้อมูลมีความแตกต่างกันไปแล้วแต่วัตถุประสงค์ในการใช้งาน ซึ่ง จะต้องพิจารณาเลือกใช้ และเรียนรู้เทคนิคในการจัดการต่างๆ ถ้าเลือกภาษา python ก็มีวิธีการจัดการต่างๆที่หลากหลาย ขึ้นอยู่กับว่า เรารู้วิธีใช้งานอย่างไร


เพื่อเป็นกำลังใจแก่ผู้เขียน อยากให้ช่วยกด google ads ทั้งด้านข้างและระหว่างบทสัก 2-3 click ให้ด้วยนะครับ 



สรุปประเภทการจัดเก็บของข้อมูลในภาษา python ตอนที่ 2 


1️⃣ จากตอนที่ 1 ได้เกริ่นนำเกี่ยวกับ การจัดเก็บข้อมูล ชนิดต่างๆ ได้แก่ List, Tuple, String ซึ่ง ทั้ง 3 วิธีการจัดเก็บข้อมูลนี้ จะเกี่ยวข้องและใช้งานร่วมกันกับการเก็บข้อมูลในตอนที่ 2 นี้มาก โดยส่วนใหญ่การเขียนโปรแกรม Python จะใช้วิธีการจัดเก็บของตอนที่ 2 นี้ค่อนข้างมากที่สุด ในบรรดาการเก็บข้อมูล สามารถอ่านย้อนหลัง การจัดเก็บข้อมูล List, Tuple, String ใน ตอนที่ 1 ด้านบน 


2️⃣ สำหรับตอนที่ 2 นี้ จะสรุปถึงการจัดการเก็บข้อมูลชนิด Dictinary หรือ ถ้าโดยทั่วไปจะเรียกมันว่า JSON "JavaScript Object Notation” สำหรับ คนที่เขียน Web service หรือ Web Application ไม่ว่าจะเป็นการทำ API หรือ Frontend จะค่อนข้างคุ้นเคยกันเป็นอย่างดี ซึ่ง JSON ถึงนำมาใช้เป็น Protocol ให้การสื่อสารระหว่าง Server กับ Server หรือ User กับ Server ซึ่ง Dictinary และ JSON ทั้ง 2 มีความคล้ายกันในเรื่องของโครงสร้างข้อมูลที่ใช้ในการเก็บข้อมูลในรูปแบบ Key และ Value เช่น {"name": "John", "age": 30}

3️⃣ ในสถานการณ์ต่างๆ dictinary จะมีการเก็บข้อมูลหลายอย่างรวมกัน เช่น

my_dict = {
    "name": "sklsongkiat",
    "address": ("123 Main Street", "thailand", "bangkok"),
    "hobbies": ["reading", "programming", "datascience"],
    "contacts": {
        "email": "[email protected]",
        "phone": "+1234567890"
    }
}

4️⃣ ส่วนใหญ่ไม่เห็นการนำ Tuple ใช้ในการทำ web service แต่จะเป็นการแปลงจาก tuple ไปเป็น dictinary ซึ่งจะประกอบด้วย nest dict และ list สำหรับบทความนี้ อาจจะมีการยกตัวอย่างในการจัดการข้อมูล Dictinary ร่วมกับ Tuple ด้วย ด้วยข้อดีของแต่ละวิธีการจัดเก็บข้อมูลที่แตกต่างกัน จึงจำเป็นจัดเก็บต่างกันแล้วแปลงข้อมูล ไปมา

5️⃣ เราสามารถที่จะจัดการข้อมูลใน dictinary อย่างไรได้บ้าง เช่นเดียวกันกับ การจัดเก็บแบบอื่นๆ แต่คำสั่งที่ใช้แตกต่างกัน สำหรับตอนที่ 2 นี้จะมาเขียนสรุปแต่ละวิธีกัน ได้แก่

  • การสร้าง dictinary (create)
  • การจัดเรียง (sort)
  • การเข้าถึงข้อมูล (access, get)
  • การแก้ไขข้อมูล (alter, update)
  • การลบข้อมูล (remove)
  • การแตกข้อมูล (unpacking)
  • การค้นหา (finding)
  • ——————— *

  • 1️⃣0️⃣0️⃣ หากใครไม่อยากพลาด *

  • โพสต์เรื่องเกี่ยวกับ *

  • data analyst, data science, *

  • data engineer และ programming *

  • ในโพสต์ถัดๆไป ฝากแชร์ *

  • กดติดตาม profile กันไว้ด้วยนะครับ *

  • *——————— **

6️⃣ การสร้าง dictinary (create)

เราสามารถใช้คำสั่ง dict() หรือ สามารถใช้วงเล็บปีกกา ในการสร้าง dictinary ได้ ตัวอย่างเช่น

# Create an empty dictionary with dict method
art_galleries = dict()

# Create an empty dictionary with short 
art_galleries = {}

7️⃣ สามารถที่จะสร้างข้อมูลที่เป็น Tuple แปลงให้เป็น dictinary ได้ด้วยการใช้ dict() method

galleries = [('Museum of Modern Art', '10019'), ('Metropolitan Museum of Art', '10028')]
art_galleries = dict(galleries)

8️⃣ การจัดเรียง (sort) ยกตัวอย่าง เราจะสร้าง dict เปล่าๆขึ้นมาเพื่อรับค่าจาก ชุดข้อมูลอื่นที่เป็น Tuple หน้าตาแบบนี้ โดยเก็บเอาไว้ในตัวแปร squirrels ถ้าสังเกตจะเห็นว่า คู่แต่ละคู่จะประกอบไปด้วยข้อมูล park และ detail-squirrel

squirrels = [('Marcus Garvey Park', ('Black', 'Cinnamon', 'Cleaning', None)),
 ('Highbridge Park',
  ('Gray',
   'Cinnamon',
   'Running, Eating',
   'Runs From, watches us in short tree')),
 ('Madison Square Park', ('Gray', None, 'Foraging', 'Indifferent')),
 ('City Hall Park', ('Gray', 'Cinnamon', 'Eating', 'Approaches')),
 ('J. Hood Wright Park', ('Gray', 'White', 'Running', 'Indifferent')),
 ('Seward Park', ('Gray', 'Cinnamon', 'Eating', 'Indifferent')),
 ('Union Square Park', ('Gray', 'Black', 'Climbing', None)),
 ('Tompkins Square Park', ('Gray', 'Gray', 'Lounging', 'Approaches'))]

9️⃣ เริ่มต้นสร้าง dictinary เพื่อมารับค่าจาก tuple

# Create an empty dictionary: squirrels_by_park
squirrels_by_park = dict()

???? หากยังจำกันได้ ว่าในตอนที่ 1 เราได้เรียนวิธีการ uppack tuple เพื่อแยก ระหว่างการจับคู่ออกจากกัน (unpair) เราจะใช้วิธีการ iterable หรือ loop เข้ามาช่วย จะเห็นว่า key คือ index และ park เพื่อจัดเก็บ key index เข้าไปใน dictinary ที่สร้างขึ้นใหม่ และให้ key แต่ละ dict เป็นชื่อ หรือ string แทนแต่ละ element ด้วย park

for index, park  in squirrels:
    # Add each squirrel_details to the squirrels_by_park dictionary 
    squirrels_by_park[index] = park

1️⃣1️⃣ หลังจากนั้น เราจะจัดเรียง ด้วยคำสั่ง sort

# Sort the squirrels_by_park dict alphabetically by park
for park in sorted(squirrels_by_park):
    # Print each park and its value in squirrels_by_park
    print(f'{park}: {squirrels_by_park[park]}')

1️⃣2️⃣ ผลลัพท์ที่ได้

City Hall Park: ('Gray', 'Cinnamon', 'Eating', 'Approaches')
Highbridge Park: ('Gray', 'Cinnamon', 'Running, Eating', 'Runs From, watches us in short tree')
J. Hood Wright Park: ('Gray', 'White', 'Running', 'Indifferent')
Madison Square Park: ('Gray', None, 'Foraging', 'Indifferent')
Marcus Garvey Park: ('Black', 'Cinnamon', 'Cleaning', None)
Seward Park: ('Gray', 'Cinnamon', 'Eating', 'Indifferent')
Tompkins Square Park: ('Gray', 'Gray', 'Lounging', 'Approaches')
Union Square Park: ('Gray', 'Black', 'Climbing', None)

1️⃣3️⃣ การเข้าถึงข้อมูล (access, get)

เวลาที่เราจะดึงข้อมูลออกมาจาก dictinary เราจะใช้ method get() โดยมีวิธีดังนี้

1️⃣4️⃣ ตอนนี้เราได้จัดเก็บข้อมูลใหม่ อยู่ใน squirrels_by_park หน้าตาแบบนี้ จะเห็ยว่ามี key ที่เป็น park และ value เป็น tuple แล้วครอบด้วย dictinary เหมือนการจัดเก็บด้วยสมุด หนังสือ

squirrels_by_park = {'Marcus Garvey Park': ('Black', 'Cinnamon', 'Cleaning', None),
 'Highbridge Park': ('Gray',
  'Cinnamon',
  'Running, Eating',
  'Runs From, watches us in short tree'),
 'Madison Square Park': ('Gray', None, 'Foraging', 'Indifferent'),
 'City Hall Park': ('Gray', 'Cinnamon', 'Eating', 'Approaches'),
 'J. Hood Wright Park': ('Gray', 'White', 'Running', 'Indifferent'),
 'Seward Park': ('Gray', 'Cinnamon', 'Eating', 'Indifferent'),
 'Union Square Park': ('Gray', 'Black', 'Climbing', None),
 'Tompkins Square Park': ('Gray', 'Gray', 'Lounging', 'Approaches')}

1️⃣5️⃣ ถ้าเราอยากจะเข้าถึง key ชื่อ Union Square Park ให้ใช้คำสั่ง get แบบนี้ และ ผลลัพท์ข้อมูล ที่ map กับ key

print(squirrels_by_park.get('Union Square Park'))

#
('Gray', 'Black', 'Climbing', None)

1️⃣6️⃣ การแก้ไขข้อมูล (alter, update)

หากยังจำกันได้ การจัดเก็บข้อมูลจะสามารถเปลี่ยนแปลงได้ (mutable) และ เปลี่ยนแปลงไม่ได้ (immutable) ซึ่ง dintinary เป็นแบบเปลี่ยนแปลงได้ เราสามารถใช้ method update() ในการแก้ไขข้อมูลที่เราต้องการ เช่น ถ้าเรามี list ชื่อ Union Square Park อยู่ใน dintinary squirrels_by_park แล้วต้องการ update squirrels_union

squirrels_union = [{'primary_fur_color': 'Gray',
  'highlights_in_fur_color': None,
  'activities': 'Sitting',
  'interactions_with_humans': 'Indifferent'}]

1️⃣7️⃣ squirrels_by_park มีข้อมูล

print(squirrels_by_park)
##
{'Union Square Park': []}

1️⃣8️⃣ ทำการ update

squirrels_by_park.update([squirrels_union])

1️⃣9️⃣ ได้ผลลัพท์

{'Union Square Park': [{'primary_fur_color': 'Gray',
  'highlights_in_fur_color': None,
  'activities': 'Sitting',
  'interactions_with_humans': 'Indifferent'}}

2️⃣0️⃣ การลบข้อมูล (remove)

ถ้าเกิดว่า เราไม่ต้องการข้อมูลใน dictinary แล้วเราต้องทำอย่างไร เราสามารถใช้คำสั่ง pop method

2️⃣1️⃣ สมมติว่าเรามี dictinary หน้าตาแบบนี้ มี key ที่ประกอบไปด้วย

  • 'Madison Square Park'
  • 'Tompkins Square Park'
  • 'Union Square Park'

โดยต้องการจะลบ Madison Square Park

print(squirrels_by_park)

{'Madison Square Park': [{'primary_fur_color': 'Gray',
   'highlights_in_fur_color': None,
   'activities': 'Foraging',
   'interactions_with_humans': 'Indifferent'}],
 'Tompkins Square Park': [{'primary_fur_color': 'Gray',
   'highlights_in_fur_color': 'Gray',
   'activities': 'Foraging',
   'interactions_with_humans': 'Approaches'},
  {'primary_fur_color': 'Gray',
   'highlights_in_fur_color': 'Gray',
   'activities': 'Climbing (down tree)',
   'interactions_with_humans': 'Indifferent'}],
 'Union Square Park': [{'primary_fur_color': 'Gray',
   'highlights_in_fur_color': None,
   'activities': 'Eating, Foraging',
   'interactions_with_humans': None}]}

2️⃣2️⃣ ใช้คำสั่ง pop จะทำการดึงข้อมูลออกจาก dictinary จากตัวอย่าง สามารถที่จะ pop ออกมาเก็บเอาไว้ที่ squirrels_madison ได้

# Remove "Madison Square Park" from squirrels_by_park
squirrels_madison = squirrels_by_park.pop("Madison Square Park")

## 
print(squirrels_madison)

[{'primary_fur_color': 'Gray',
  'highlights_in_fur_color': None,
  'activities': 'Foraging',
  'interactions_with_humans': 'Indifferent'}]

2️⃣3️⃣ คราวนี้เรามาดูว่าตัวแปร squirrels_by_park กับ key ชื่อ "Madison Square Park" หายไปแล้วหรือไม่

print(squirrels_by_park)

{'Tompkins Square Park': [{'primary_fur_color': 'Gray',
   'highlights_in_fur_color': 'Gray',
   'activities': 'Foraging',
   'interactions_with_humans': 'Approaches'},
  {'primary_fur_color': 'Gray',
   'highlights_in_fur_color': 'Gray',
   'activities': 'Climbing (down tree)',
   'interactions_with_humans': 'Indifferent'}],
 'Union Square Park': [{'primary_fur_color': 'Gray',
   'highlights_in_fur_color': None,
   'activities': 'Eating, Foraging',
   'interactions_with_humans': None}]}

2️⃣4️⃣ การแตกข้อมูล (unpacking)

ในการ unpack หรือการจะแตก key กับ value มีด้วยกันหลายวิธี มักจะใช้ร่วมกับ loop หรือ iterabe โดยใช้คำสั่ง items() method เช่น จาก ตัวแปรเดิมที่มีข้อมูล "Madison Square Park" อยู่

for field, value in squirrels_by_park["Madison Square Park"][0].items():
    # Print field and value
    print(field, value)

##

primary_fur_color Gray
highlights_in_fur_color None
activities Foraging
interactions_with_humans Indifferent

2️⃣5️⃣ nested dictionaries

บ่อยครั้งที่เราจะมีการ เก็บ dictinary แบบซ้อนๆกัน เช่น

print(squirrels_by_park)

##
{'J. Hood Wright Park': {'primary_fur_color': 'Gray',
  'highlights_in_fur_color': 'Cinnamon',
  'activities': 'Running',
  'interactions_with_humans': 'Indifferent'},
 'Stuyvesant Square Park': {'primary_fur_color': 'Gray',
  'highlights_in_fur_color': 'Cinnamon',
  'activities': 'Foraging',
  'interactions_with_humans': 'Indifferent'},
 'Highbridge Park': {'primary_fur_color': 'Gray',
  'highlights_in_fur_color': 'White',
  'activities': 'Climbing',
  'interactions_with_humans': None},
 'Tompkins Square Park': {'primary_fur_color': 'Gray',
  'highlights_in_fur_color': 'Gray',
  'activities': 'Foraging',
  'interactions_with_humans': None},
 'Union Square Park': {'primary_fur_color': 'Gray',
  'activities': 'Eating, Foraging',
  'interactions_with_humans': None},
 'City Hall Park': {'primary_fur_color': 'Gray',
  'highlights_in_fur_color': 'White',
  'activities': 'Eating, Foraging',
  'interactions_with_humans': 'Indifferent'},
 'Msgr. McGolrick Park': {'primary_fur_color': 'Gray',
  'highlights_in_fur_color': 'Cinnamon',
  'activities': 'Running',
  'interactions_with_humans': 'Indifferent'},
 'John V. Lindsay East River Park': {'primary_fur_color': 'Gray',
  'highlights_in_fur_color': 'Gray',
  'activities': 'Running, Chasing, Eating',
  'interactions_with_humans': None}}

2️⃣6️⃣ สามารถที่จะเช็คข้อมูลก่อนได้ว่ามี key อะไรบ้างใน dictinary โดยใช้ keys

print(squirrels_by_park.keys())

##

dict_keys([
'J. Hood Wright Park', 
'Stuyvesant Square Park', 
'Highbridge Park', 
'Tompkins Square Park', 
'Union Square Park', 
'City Hall Park', 
'Msgr. McGolrick Park', 
'John V. Lindsay East River Park'])

2️⃣7️⃣ เราสามารถที่จะ check key ว่ามีอยู่หรือไม่ใน dict ด้วย คำสั่ง in

# Check to see if Tompkins Square Park is in squirrels_by_park
if "Tompkins Square Park" in squirrels_by_park:
    # Print 'Found Tompkins Square Park'
    print('Found Tompkins Square Park')
    
# Check to see if Central Park is in squirrels_by_park
if "Central Park" in squirrels_by_park:
    # Print 'Found Central Park' if found
    print('Found Central Park')
else:
    # Print 'Central Park missing' if not found
    print('Central Park missing')

##

Found Tompkins Square Park
Central Park missing

2️⃣8️⃣ ซึ่งขั้นตอนทั้งหมด ที่กล่าวมักจะใช้ร่วมกัน เพื่อจัดข้อมูลที่เป็น dictinary

# Use a for loop to iterate over the squirrels in Tompkins Square Park:
for squirrel in squirrels_by_park["Tompkins Square Park"]:
	# Safely print the activities of each squirrel or None
    print(squirrel.get("activities"))
    
##

Foraging
Climbing (down tree)
None
Foraging

    
# Print the list of 'Cinnamon' primary_fur_color squirrels in Union Square Park
print([squirrel for squirrel in squirrels_by_park["Union Square Park"] if "Cinnamon" in squirrel['primary_fur_color']])

##
[{'primary_fur_color': 'Cinnamon', 'highlights_in_fur_color': None, 'activities': 'Foraging', 'interactions_with_humans': None}]


1️⃣0️⃣0️⃣ โดยสรุป ประเภทของการจัดเก็บข้อมูล แบบ dictinary มีการใช้งานมากที่สุดและสามารถประยุกต์ใช้กับงานอื่นๆ เช่น web service API หรือ ทำ Web Application ด้วย ซึ่งจะต้องเรียนรู้เทคนิคในการจัดการต่างๆ ถ้าเลือกภาษา python ก็มีวิธีการจัดการต่างๆที่หลากหลาย ขึ้นอยู่กับว่า เรารู้วิธีใช้งานอย่างไร


เพื่อเป็นกำลังใจแก่ผู้เขียน อยากให้ช่วยกด google ads ทั้งด้านข้างและระหว่างบทสัก 2-3 click ให้ด้วยนะครับ 


สรุปประเภทการจัดเก็บของข้อมูลในภาษา python ตอนที่ 3

1️⃣ จากตอนที่ 1 และ 2 ได้เขียนถึงวิธีการจัดเก็บข้อมูล ชนิดต่างๆ ได้แก่ List, Tuple, String และ Dictinary ในตอนที่ 2 เขียนถึงวิธีการจัดการข้อมูลต่างๆใน dictinary ที่ใช้วิธีการจัดเก็บร่วมกันกับ List, Tuple, String อ่านย้อนหลังได้ด้านบน


2️⃣ สำหรับตอนที่ 3 จะเขียนถึงวิธีการจัดเก็บอีกหนึ่งชนิดที่ใช้มากในการคำนวนทางคณิตศาสตร์ นั่นคือ การจัดเก็บข้อมูลประเภท Set

3️⃣ set มีรูปแบบการจัดเก็บและรูปที่ใช้วงเล็บปีกกา {} เพื่อกำหนดค่าของเซต มีหน้าตาแบบนี้ {1, 2, 3, 4, 5}

4️⃣ set มีคุณสมบัติในการเก็บข้อมูลดังต่อไปนี้

  • unique หรือ ค่าที่ไม่ซ้ำกัน
  • ไม่เรียงลำดับ (unorder)
  • เปลี่ยนแปลงค่าได้ (mutable)
  • ใช้งานกับงานทางคณิตศาสตร์ อย่างที่เกริ่นไปข้างต้น (Set Theory)

5️⃣ เราสามารถที่จะจัดการข้อมูลใน Set ได้เช่นเดียวกันกับ Dictinary ได้แก่

  • การสร้าง set (create)
  • การเพิ่มข้อมูล (modify sets)
  • การแก้ไขข้อมูล (updaet sets)
  • การลบข้อมูล (remove)
  • การหาความคล้ายกัน (set operaion)
  • ——————— *

  • 1️⃣0️⃣0️⃣ หากใครไม่อยากพลาด *

  • โพสต์เรื่องเกี่ยวกับ *

  • data analyst, data science, *

  • data engineer และ programming *

  • ในโพสต์ถัดๆไป ฝากแชร์ *

  • กดติดตาม profile กันไว้ด้วยนะครับ *

  • *——————— **

6️⃣ การสร้าง set (create)

การใช้ฟังก์ชัน set() ซึ่งวิธีนี้อาจกำหนดสมาชิก ในรูปแบบของลิสต์หรือทูเพิลก็ได้ ยกตัวอย่าง

สร้าง set ด้วย list

s = set([1, 2, 3])
print(s)

##
{1, 2, 3}

7️⃣ สร้าง set ด้วย tuple

s = set((1, 2, 3))
print(s)

##
{1, 2, 3}

8️⃣ ยกตัวอย่างคุณสมบัติที่เป็น unique ถ้าสมมติว่า เรามีข้อมูลที่มีค่า ซ้ำๆกันอยู่ list แบบนี้ แล้วนำเข้า set มันจะแสดงค่าเฉพาะค่าที่ไม่ซ้ำกัน

duplicate = [1, 2, 3, 2, 1]
s = set(t)
print(s)

##
{1, 2, 3}

9️⃣ การเพิ่มข้อมูล (modify sets)

หากเราต้องการเพิ่มข้อมูลเข้าไปใน set แค่ตัวเดียวเราสามารถใช้ method ชื่อ add กับ set ได้ ยกตัวอย่าง

s = {1, 2, 3}
s.add(4)
print(s)

##
{1, 2, 3, 4}

1️⃣0️⃣ ถ้าหากอยากจะเพิ่มหลายๆตัวเข้าไปใน set ให้ใช้ method update ยกตัวอย่าง

s = {1, 2, 3}
s.update({5, 6, 7})
print(s)

## 
{1, 2, 3, 4, 5, 6, 7}

1️⃣1️⃣ การลบข้อมูล (remove)

หากเราต้องการลบข้อมูลออกจาก set สามารถใช้ method ชื่อ discard, remove หรือ pop ได้ ซึ่งทั้ง 3 method ใช้ลบเหมือนกัน pop จะมีลักษณะที่ไม่ใช่การลบออกไปทันที แต่เป็นการดึงออกไปเก็บไว้ที่อื่น เช่น

s = {1, 2, 3}
x = s.pop()
print(s)
print(x)

1️⃣2️⃣ ข้อควรระวัง remove หรือ pop ควรใช้ลบในกรณีที่ เรารู้ว่ามีข้อมูลแน่ๆ เพราะถ้าใช้ลบข้อมูลตอนที่มันไม่มีหรือค่าว่าง มันจะเกิด error แต่ discard ไม่เกิด error ยกตัวอย่าง

s = {1, 2, 3}
s.remove(2)
print(s)

##
{1, 3}

1️⃣3️⃣ ส่วน discard

s = {1, 2, 3}
s.discard(2)
print(s)

##
{1, 3}

1️⃣4️⃣ การหาความคล้ายกัน (set operaion)

จากคุณสมบัติ ที่สามารถใช้คำนวนทางคณิตศาสตร์ได้ คือ สามารถใช้ตรวจสอบความแตกต่าง หรือ เหมือนกันของข้อมูลที่เป็น set 2 ตัวได้ โดยใช้ method difference , intersection และ union

1️⃣5️⃣ difference ตรวจสอบความต่างและดึงค่าที่ต่างกันมาเก็บเป็นข้อมูล ยกตัวอย่างเช่น เรามีชุดข้อมูลนกเพนกวินอยู่ โดยทำ List Comprehension เพื่อลดจำนวนบรรทัด การเขียน code ให้อยู่ใน บรรทัดเดียว โดยมี dataset หน้าตาแบบนี้

print(penguins)

[
	{'species': 'Adlie',
	  'flipper_length': 190.0,
	  'body_mass': 3050.0,
	  'sex': 'FEMALE'},
	 {'species': 'Adlie',
	  'flipper_length': 184.0,
	  'body_mass': 3325.0,
	  'sex': 'FEMALE'},
	 {'species': 'Gentoo',
	  'flipper_length': 209.0,
	  'body_mass': 4800.0,
	  'sex': 'FEMALE'},
	 {'species': 'Adlie',
	  'flipper_length': 193.0,
	  'body_mass': 4200.0,
	  'sex': 'MALE'},
	 ... 
]

1️⃣6️⃣ นำมาเข้า List Comprehension function เราจะได้สายพันธ์ของนกเพนกวินมาเก็บเอาไว้ใน list array

female_species_list = [penguin["species"] for penguin in penguins if penguin["sex"] == 'FEMALE']

#

['Adlie',
 'Adlie',
 'Gentoo',
 'Gentoo',
 'Gentoo',
 'Chinstrap',
 'Chinstrap',
 'Chinstrap',
 'Adlie',
 'Gentoo',
 'Adlie',
 'Chinstrap',
 'Adlie',
 'Gentoo']

1️⃣7️⃣ จากนั้นเราก็แปลง female_species_list ให้เป็น set จะเห็นว่า จากข้อมูล list ที่มีค่าซ้ำๆ เหลือเพียงแค่ 3 สายพันธ์ ในชุดข้อมูล set

female_penguin_species = set(female_species_list)

##
{'Adlie', 'Chinstrap', 'Gentoo'}

1️⃣8️⃣ ก่อนที่จะใช้ method difference เราดูชุดข้อมูลที่ต้องการเปรียบเทียบก่อน

print(male_penguin_species)

##
{'Adlie', 'Gentoo'}

1️⃣9️⃣ ทำการเปรียบเทียบ จะเห็นว่ามีเพียง 'Chinstrap' เท่านั้นที่ไม่ได้อยู่ใน set ทั้ง 2 ชุด

differences = female_penguin_species.difference(male_penguin_species)
print(differences)

##
{'Chinstrap'}

2️⃣0️⃣ ลองใช้ union จะดึงค่าออกมาจาก set ทั้ง 2 ชุด

all_species = female_penguin_species.union(male_penguin_species)
print(all_species)

##
{'Adlie', 'Chinstrap', 'Gentoo'}

2️⃣1️⃣ ลองใช้ intersection จะเห็นว่าจาก difference ตรงที่ดึงค่าที่ทับซ้อนกันออกมา

overlapping_species = female_penguin_species.intersection(male_penguin_species)
print(overlapping_species)

##
{'Adlie', 'Gentoo'}


1️⃣0️⃣0️⃣ โดยสรุป การใช้วิธีจัดเก็บข้อมูลแบบ set เราสามารถใช้คุณสมบัติต่างๆ มาช่วยจัดการข้อมูลที่ ซ้ำซ้อนมีค่าซ้ำๆ และ รวมข้อมูล หรือ แยกความแตกต่างระหว่างข้อมูลด้วยกันได้



เพื่อเป็นกำลังใจแก่ผู้เขียน อยากให้ช่วยกด google ads ทั้งด้านข้างและระหว่างบทสัก 2-3 click ให้ด้วยนะครับ 



สรุปการจัดเก็บข้อมูลด้วยเครื่องมือในภาษา python ตอนที่ 4 (จบ) 

1️⃣ จากตอนที่ 1, 2 และ 3 ได้เขียนถึงวิธีการจัดเก็บข้อมูล ชนิดต่างๆ ได้แก่ List, Tuple, String, Dictinary และ Set อ่านย้อนหลังได้

2️⃣ สำหรับตอนที่ 4 เขียนสรุป การใช้เครื่องมือมาช่วยทำให้การดูข้อมูล หรือ สำรวจข้อมูลด้วย Python ง่ายขึ้น


3️⃣ หลังจากที่ รู้ container ต่างๆที่ใช้ในการเก็บข้อมูลด้วยภาษา Python กันแล้ว และ หลายๆคนที่ตามอ่านบทความของผม ก็น่าจะเข้าใจในเรื่องของการสำรวจข้อมูลด้วย SQL เพียงแค่บทความนี้ เราใช้เครื่องมือที่เป็น ภาษา Python หากใครยังไม่รู้ว่าการสำรวจข้อมูลต้องทำอะไรบ้าง ตามอ่านบทความย้อนหลังกันได้ครับ

4️⃣ จากที่เคยเกริ่นไปในบทก่อนๆ การเก็บข้อมูลจะเก็บด้วย Dictinary มากที่สุด ซึ่งเครื่องมือในการสำรวจข้อมูลก็ใช้สำรวจข้อมูลใน Dictinary เช่นกัน

5️⃣ เครื่องมือที่ว่านี้ เป็น โมดูลที่เป็นส่วนหนึ่งของไลบรารีมาตรฐานใน Python ที่ชื่อว่า Collections

  • ——————— *

  • 1️⃣0️⃣0️⃣ หากใครไม่อยากพลาด *

  • โพสต์เรื่องเกี่ยวกับ *

  • data analyst, data science, *

  • data engineer และ programming *

  • ในโพสต์ถัดๆไป ฝากแชร์ *

  • กดติดตาม profile กันไว้ด้วยนะครับ *

  • *——————— **

6️⃣ Collections ประกอบไปด้วยการเรียกใช้ Class ต่างๆ เช่น

  • Counter
  • defaultdict
  • namedtuples

7️⃣ และ เครื่องมือที่จัดการข้อมูลที่ซับซ้อนชื่อ dataclasses โดยมี class ชื่อว่า dataclass โดยมีประโยชน์ใช้สร้าง Object ข้อมูลเหมือนกับการสร้าง Class ใน OOP ช่วยให้เรียกใช้ข้อมูลได้ง่ายขึ้นกว่าการเรียกข้อมูลใน Dictinary ปกติ

8️⃣ Counter

ประโยชน์ของ Counter ช่วยในการนับจำนวนที่มี key ซ้ำๆ ภายใน Dictinary ไม่ต้อง unpack ข้อมูลแล้วมา sum เอง method Counter ช่วยนับให้แล้วแสดงใน object นั้นๆได้เลย ยกตัวอย่างเช่น

9️⃣ มี dataset penguin ที่มีข้อมูลดังนี้

print(penguins)

[
	{'Species': 'Gentoo',
  'Flipper Length (mm)': 230.0,
  'Body Mass (g)': 5500.0,
  'Sex': 'MALE'},
 {'Species': 'Chinstrap',
  'Flipper Length (mm)': 201.0,
  'Body Mass (g)': 4300.0,
  'Sex': 'MALE'},
 {'Species': 'Adlie',
  'Flipper Length (mm)': 180.0,
  'Body Mass (g)': 3800.0,
  'Sex': 'MALE'},
 {'Species': 'Gentoo',
  'Flipper Length (mm)': 229.0,
  'Body Mass (g)': 5800.0,
  'Sex': 'MALE'},
	 ...
]

???? โจทย์บอกว่าอยากรู้จำนวน เพศของเพนกวินแต่ละตัวว่ามีจำนวนเท่าไร

# Import the Counter object
from collections import Counter

# Create a Counter of the penguins sex using a list comp
penguins_sex_counts = Counter(penguin['Sex'] for penguin in penguins)

# Print the penguins_sex_counts
print(penguins_sex_counts)

##

Counter({'MALE': 15, 'FEMALE': 5})

1️⃣1️⃣ ทั้งยังมี method ที่ชื่อ most_common ช่วยในการดูว่าค่าไหนใน dictinary มีค่ามากที่สุดโดยกำหนดจำนวน ค่าที่มากที่สุดได้ ยกตัวอย่าง ดูจำนวนเพนกวินของสายพันธ์ที่มากที่สุด 3 อันดับ เช่น

# Import the Counter object
from collections import Counter

# Create a Counter of the penguins list: penguins_species_counts
penguins_species_counts = Counter(penguin['Species'] for penguin in penguins)

# Find the 3 most common species counts
print(penguins_species_counts.most_common(3))

[('Chinstrap', 7), ('Adlie', 7), ('Gentoo', 6)]

1️⃣2️⃣ defaultdict

บ่อยครั้งที่ ข้อมูลใน dictinary จะมาแบบไม่มี key เช่นหน้าตาแบบนี้ ในลักษณะของ tuple ที่ไม่มี key ทำให้เรียกข้อมูลได้ค่อนข้างยาก

print(weight_log)

[('Chinstrap', 'FEMALE', 3800.0),
 ('Adlie', 'FEMALE', 3450.0),
 ('Gentoo', 'FEMALE', 4300.0),
 ('Adlie', 'FEMALE', 3550.0),
 ('Adlie', 'FEMALE', 3175.0)]

1️⃣3️⃣ โดยปกติถ้าเราไม่ใช้ defaultdict เราจะใช้ วิธีการ loop หรือ iterate ค่าแล้วดึงข้อมูลใส่ key ให้กับข้อมูล ดังนี้

# Create an empty dictionary: female_penguin_weights
female_penguin_weights = dict()

# Iterate over the weight_log entries
for species, sex, body_mass in weight_log:
    # Check to see if species is already in the dictionary
    if species not in female_penguin_weights:
        # Create an empty list for any missing species
        female_penguin_weights[species] = []
    # Append the sex and body_mass as a tuple to the species keys list
    female_penguin_weights[species].append((sex, body_mass))

		print(female_penguin_weights)

		##
		{'Chinstrap': [('FEMALE', 3800.0)],
		 'Adlie': [('FEMALE', 3450.0), ('FEMALE', 3550.0), ('FEMALE', 3175.0)],
		 'Gentoo': [('FEMALE', 4300.0)]}
    
# Print the weights for 'Adlie'
print(female_penguin_weights['Adlie'])

[('FEMALE', 3450.0), ('FEMALE', 3550.0), ('FEMALE', 3175.0)]

1️⃣4️⃣ แต่เมื่อเราใช้ defaultdict ในการสร้าง key จะเห็นว่าเขียนสั้นกว่ามาก แล้วแปลงเป็น tuple เพื่อจับคู่ข้อมูลได้ด้วย

# Import defaultdict
from collections import defaultdict

# Create a defaultdict with a default type of list: male_penguin_weights
male_penguin_weights = defaultdict(list)

# Iterate over the weight_log entries
for species, sex, body_mass in weight_log:
    # Use the species as the key, and append the body_mass to it
    male_penguin_weights[species].append(body_mass)

		print(male_penguin_weights)

		##

		defaultdict(list,
            {'Gentoo': [5500.0, 5800.0, 5400.0, 5250.0, 4925.0],
             'Chinstrap': [4300.0, 4100.0, 4800.0, 3950.0, 3800.0, 4050.0],
             'Adlie': [3800.0, 3975.0, 3950.0, 3650.0]})
    
# Print the first 2 items of the male_penguin_weights dictionary
print(list(male_penguin_weights.items())[:2])

##

[('Gentoo', [5500.0, 5800.0, 5400.0, 5250.0, 4925.0]), ('Chinstrap', [4300.0, 4100.0, 4800.0, 3950.0, 3800.0, 4050.0])]

1️⃣5️⃣ namedtuples

namedtuple เป็นโครงสร้างข้อมูลที่ผสม tuple กับ dictinary เข้าด้วยกัน ช่วยให้คุณสามารถสร้าง tuple ที่มีชื่อข้อมูล หรือ หน้าตาเหมือน Data Object ทำให้อ่านง่ายและเข้าถึงข้อมูลได้ง่ายขึ้นเมื่อเทียบกับ Tuple ปกติ เช่น สร้าง Data Object ชื่อ SpeciesDetails ขึ้นมาโดยใส่ attribute 'species', 'sex' และ 'body_mass' ของเพนกวินเข้าไป

# Import namedtuple from collections
from collections import namedtuple

# Create the namedtuple: SpeciesDetails
SpeciesDetails = namedtuple('SpeciesDetails', ['species', 'sex', 'body_mass'])

print(SpeciesDetails)

##

__main__.SpeciesDetails

1️⃣6️⃣ จากนั้นก็นำ Data Object ที่ได้ มาใส่ข้อมูลลงไป

# Create the empty list: labeled_entries
labeled_entries = []

# Iterate over the weight_log entries
for species, sex, body_mass in weight_log:
    # Append a new SpeciesDetails namedtuple instance for each entry to labeled_entries
    labeled_entries.append(SpeciesDetails(species, sex, body_mass))
    
print(labeled_entries[:5])

## 

[SpeciesDetails(species='Gentoo', sex='MALE', body_mass=5500.0), SpeciesDetails(species='Chinstrap', sex='MALE', body_mass=4300.0), SpeciesDetails(species='Adlie', sex='MALE', body_mass=3800.0), SpeciesDetails(species='Gentoo', sex='MALE', body_mass=5800.0), SpeciesDetails(species='Chinstrap', sex='MALE', body_mass=4100.0)]

1️⃣7️⃣ และสุดท้าย Dataclass มีประโยชน์มากในการเรียกใช้ข้อมูล โดยมีการสร้าง Class แล้ว เรียกใช้อีกที สามารถสร้างได้แบบนี้ โดยสังเกตว่า property จะมีการคำนวนเอาไว้ใน method ด้วย เวลาที่ดึงค่าออกมาจะได้ข้อมูลที่คำนวนไว้แล้ว

@dataclass
class WeightEntry:
    # Define the fields on the class
    species: str
    flipper_length: int
    body_mass: int
    sex: str

    @property
    def mass_to_flipper_length_ratio(self):
        return self.body_mass / self.flipper_length

1️⃣8️⃣ แล้วเรียกใช้ Class WeightEntry

# Create the empty list: labeled_entries
labeled_entries = []

# Iterate over the weight_log entries
for species, sex, flipper_length, body_mass in weight_log:
    # Append a new WeightEntry instance to labeled_entries
    labeled_entries.append(WeightEntry(species, body_mass, flipper_length, sex))

print(labeled_entries)

##

[WeightEntry(species='Gentoo', flipper_length=230.0, body_mass=5500.0, sex='MALE'),
 WeightEntry(species='Gentoo', flipper_length=229.0, body_mass=5800.0, sex='MALE'),
 WeightEntry(species='Gentoo', flipper_length=225.0, body_mass=5400.0, sex='MALE'),
 WeightEntry(species='Gentoo', flipper_length=219.0, body_mass=5250.0, sex='MALE'),
 WeightEntry(species='Gentoo', flipper_length=210.0, body_mass=4300.0, sex='FEMALE'),
 WeightEntry(species='Gentoo', flipper_length=216.0, body_mass=4925.0, sex='MALE')]

1️⃣9️⃣ เรียก property ข้อมูล แล้วแสดงผลจะได้แบบน

# Print a list of the first 5 mass_to_flipper_length_ratio values
print([entry.mass_to_flipper_length_ratio for entry in labeled_entries[:5]])

##

[23.91304347826087, 25.32751091703057, 24.0, 23.972602739726028, 20.476190476190474]

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


เพื่อเป็นกำลังใจแก่ผู้เขียน อยากให้ช่วยกด google ads ทั้งด้านข้างและระหว่างบทสัก 2-3 click ให้ด้วยนะครับ 

แวะมาทักทายกันได้
donate