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

การสร้าง Series จาก NumPy Array พร้อมกำหนด Index เองใน Pandas Python

Pandas Series สร้างจาก NumPy Array ได้ และสามารถกำหนด Custom Index แทน Default Integer Index

ตัวอย่างโค้ด


import pandas as pd
import numpy as np

# NumPy Array ของ Strings
my_data = np.array(['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi'])

# Custom Index (ไม่ต่อเนื่อง, ไม่เรียง)
my_index = [3, 5, 7, 9, 11, 23, 45, 67]

my_series = pd.Series(my_data, index=my_index)

print("Series from NumPy array with custom index:")
print(my_series)

ผลลัพธ์


Series from NumPy array with custom index:
3   ab
5   bc
7   cd
9   de
11  ef
23  fg
45  gh
67  hi
dtype: object

คำอธิบาย

  • สร้าง NumPy Array ด้วย np.array([...])

  • กำหนด Custom Index List (Integer แต่ไม่ต่อเนื่อง)

  • สร้าง Series: pd.Series(data, index=index_list)

  • Array และ Index ต้องมีความยาวเท่ากัน

การสร้าง Series จาก NumPy Array แบบต่างๆ

Input DataIndexผลลัพธ์
1D Arrayไม่ระบุDefault 0..n-1
1D ArrayList/Array ความยาวเท่ากันCustom Index
2D Array (n,1)ไม่ระบุFlatten → 1D Series
ScalarList IndexBroadcast Scalar

NumPy Array vs Python List


import numpy as np
import pandas as pd

# Python List
py_list = [1, 2, 3, 4]
s1 = pd.Series(py_list)

# NumPy Array
np_arr = np.array([1, 2, 3, 4])
s2 = pd.Series(np_arr)

# ทั้งคู่ให้ผลลัพธ์เหมือนกัน
print(s1.equals(s2))  # True

Dtype Inference


# Numeric Array → Numeric Dtype
np.array([1, 2, 3])        → int64
np.array([1.0, 2.0, 3.0])  → float64
np.array([1, 2.5, 3])      → float64 (Upcast)

# String Array → Object Dtype
np.array(['a', 'b', 'c'])  → object

# Boolean Array → bool
np.array([True, False])    → bool

# Datetime Array
np.array(['2024-01-01'], dtype='datetime64') → datetime64[ns]

Copy vs View


arr = np.array([1, 2, 3])
s = pd.Series(arr)

# Pandas มัก Copy Data (Safe)
s.iloc[0] = 999
print(arr[0])  # 1 (Original ไม่เปลี่ยน)

# แต่บางครั้งอาจ Share Memory (Depends on Version/Dtype)
# ใช้ copy=True เพื่อความแน่ใจ
s = pd.Series(arr, copy=True)