Skip to content

Series & DataFrame

pandas มีโครงสร้างข้อมูลหลัก 2 แบบ: Series (1 มิติ) และ DataFrame (2 มิติ) ทุกอย่างใน pandas สร้างจากสองตัวนี้

Series — ข้อมูล 1 มิติ

Section titled “Series — ข้อมูล 1 มิติ”
import pandas as pd
# สร้าง Series จาก list
prices = pd.Series([100, 250, 75, 430], name="price")
print(prices)
# 0 100
# 1 250
# 2 75
# 3 430
# Name: price, dtype: int64
# Series มี index
prices.index = ["A", "B", "C", "D"]
print(prices["B"]) # 250

DataFrame — ข้อมูล 2 มิติ (ตาราง)

Section titled “DataFrame — ข้อมูล 2 มิติ (ตาราง)”
# สร้าง DataFrame จาก dict
df = 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())