สามารถสร้าง Series จากค่า Scalar (ค่าคงที่) ได้ ค่าดังกล่าวจะถูก Broadcast (กระจาย) ไปทุก Element ตาม Index ที่กำหนด
ตัวอย่าง 1: Scalar Value พร้อม Custom Index
import pandas as pd
my_index = ['ab', 'mn', 'gh', 'kl']
my_series = pd.Series(7, index=my_index)
print("Series from scalar value with custom index:")
print(my_series)
ผลลัพธ์
Series from scalar value with custom index:
ab 7
mn 7
gh 7
kl 7
dtype: int64
ตัวอย่าง 2: Scalar Value โดยไม่ระบุ Index (Default)
my_series = pd.Series(7)
print("Series from scalar with default index:")
print(my_series)
ผลลัพธ์
Series from scalar with default index:
0 7
dtype: int64
คำอธิบาย
pd.Series(7, index=['a','b','c'])- สร้าง Series ความยาว 3 ทุกค่า = 7pd.Series(7)- สร้าง Series ความยาว 1 Index = [0] ค่า = 7Index Length กำหนดความยาว Series (ไม่ใช่ค่า Scalar)
การ Broadcast กับ Index ต่างๆ
# String Index
pd.Series(3.14, index=['x', 'y', 'z'])
# x 3.14
# y 3.14
# z 3.14
# DateTime Index
dates = pd.date_range('2024-01-01', periods=5)
pd.Series(100, index=dates)
# 2024-01-01 100
# 2024-01-02 100
# ...
# MultiIndex
idx = pd.MultiIndex.from_tuples([('A',1), ('A',2), ('B',1)])
pd.Series(0, index=idx)
กรณีใช้งานจริง (Use Cases)
| สถานการณ์ | ตัวอย่าง |
|---|---|
| สร้าง Constant Column | df['const'] = 1 (สำหรับ Intercept ใน Regression) |
| Initialize Column | df['status'] = 'pending' |
| Fill Missing Values | s.fillna(0) หรือ s.fillna(s.mean()) |
| Create Baseline/Reference | Benchmark Series สำหรับเปรียบเทียบ |
| Testing/Prototyping | สร้างข้อมูลทดสอบอย่างรวดเร็ว |
Dtype Control
# บังคับ dtype
pd.Series(7, index=['a','b'], dtype=float) # 7.0
pd.Series(7, index=['a','b'], dtype='int32') # 7 (int32)
pd.Series(True, index=['a','b'], dtype=bool) # True
Note: Scalar Series คล้าย Constant Array ใน NumPy: np.full(3, 7) → array([7,7,7])