Series & DataFrame
Series & DataFrame
Section titled “Series & DataFrame”pandas มีโครงสร้างข้อมูลหลัก 2 แบบ: Series (1 มิติ) และ DataFrame (2 มิติ) ทุกอย่างใน pandas สร้างจากสองตัวนี้
Series — ข้อมูล 1 มิติ
Section titled “Series — ข้อมูล 1 มิติ”import pandas as pd
# สร้าง Series จาก listprices = pd.Series([100, 250, 75, 430], name="price")print(prices)# 0 100# 1 250# 2 75# 3 430# Name: price, dtype: int64
# Series มี indexprices.index = ["A", "B", "C", "D"]print(prices["B"]) # 250DataFrame — ข้อมูล 2 มิติ (ตาราง)
Section titled “DataFrame — ข้อมูล 2 มิติ (ตาราง)”# สร้าง DataFrame จาก dictdf = pd.DataFrame({ "product": ["เสื้อ", "กางเกง", "รองเท้า", "หมวก"], "price": [350, 590, 1200, 299], "qty": [10, 5, 3, 20]})print(df)# product price qty# 0 เสื้อ 350 10# 1 กางเกง 590 5# 2 รองเท้า 1200 3# 3 หมวก 299 20ตรวจสอบโครงสร้างข้อมูล
Section titled “ตรวจสอบโครงสร้างข้อมูล”# .shape — จำนวน (แถว, คอลัมน์)print(df.shape) # (4, 3)
# .dtypes — ชนิดข้อมูลแต่ละคอลัมน์print(df.dtypes)# product object# price int64# qty int64
# .info() — สรุปข้อมูลทั้งหมดdf.info()# <class 'pandas.core.frame.DataFrame'># RangeIndex: 4 entries, 0 to 3# Data columns (total 3 columns):# # Column Non-Null Count Dtype# --- ------ -------------- -----# 0 product 4 non-null object# 1 price 4 non-null int64# 2 qty 4 non-null int64
# .head() / .tail() — ดูข้อมูลตัวอย่างprint(df.head(2)) # 2 แถวแรกprint(df.tail(2)) # 2 แถวสุดท้าย
# .describe() — สถิติเบื้องต้นprint(df.describe())- Series = คอลัมน์เดียว เช่น
A:A - DataFrame = ทั้งตาราง (sheet)
.shape= ดูจำนวนแถว/คอลัมน์จากมุมล่างซ้าย.describe()= ใช้AVERAGE(),MIN(),MAX()แยกแต่ละคอลัมน์
-- Series = SELECT column เดียวSELECT price FROM products;-- DataFrame = SELECT หลาย columnSELECT product, price, qty FROM products;-- .shapeSELECT COUNT(*) FROM products;-- .describe()SELECT AVG(price), MIN(price), MAX(price) FROM products;// C ไม่มี DataFrame ดั้งเดิม// ใช้ array of structs แทนstruct Product { char name[50]; int price; int qty; };struct Product products[4];int row_count = sizeof(products) / sizeof(products[0]);