Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การสร้าง Series จาก Scalar/Constant Value ใน Pandas Python

สามารถสร้าง 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 ทุกค่า = 7

  • pd.Series(7) - สร้าง Series ความยาว 1 Index = [0] ค่า = 7

  • Index 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 Columndf['const'] = 1 (สำหรับ Intercept ใน Regression)
Initialize Columndf['status'] = 'pending'
Fill Missing Valuess.fillna(0) หรือ s.fillna(s.mean())
Create Baseline/ReferenceBenchmark 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])