พื้นฐาน ของ numpy slicing และ indexing


พื้นฐานโดยการสร้าง slice object สร้างโดย การประกาศ start:stop:step ภายใน [ ] (brackets) ไม่รวมสมาชิกตัวที่ stop index เสมอ

ถ้า index เป็นบวก (positive) จะเริ่มนับจากทางขวา หาก index เป็น ลบ (nagative) จะนับจากทางซ้าย

#Example
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x[1:7:2]
x[-2:10]
x[-3:3:-1]

สำหรับ numpy array 2 มิติ จะสามารถอ้างอิงสมาชิกด้วย a[i,j] a[i][j] อีกทั้งสามารถใช้รูปแบบของ การประกาศแบบ slicing

#Example
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
a.shape
a[0,0]
a[2,2]
a[:,1:]
a[:,0]
a[:,0:]

ตัวอย่างแสดงให้เห็นทิศทางการนับของ index python string เป็น list เช่นเดียวกัน ผลที่ได้จะได้จากการ slice คือ list ชุดใหม่

word = "Monty Python"
word[6:10]
word[-12:-7]

เช่นเดียวกับ numpy ก็สนับสนุกการ index, slice เช่นเดียวกัน

จากรูป ให้สร้าง file data2.txt มีข้อมูลภายในดังนี้

0   1  2  3  4  5
10 11 12 13 14 15
20 21 22 23 24 25
30 31 32 33 34 35
40 41 42 43 44 45
50 51 52 53 54 55

หลังจากนั้นให้ load เข้า numpy array พร้อมกับทดสอบตามคำสั่งต่อไปนี้และให้ดูรูปด้านบนประกอบ

# Load
a = np.loadtxt('data2.txt')
a[0,3:5]
a[4:,4:]
a[2::2,::2]

ตัวอย่าง

x = np.arange(9).reshape(3,3)
x[:,0]
x.shape
y = x[::2,::2]
y[0,0]=100

ตัวอย่าง finite diffences method

x = np.arange(0,20,2)
x
y = x**2
y
dy_dx = (y[1:] - y[:-1])/(x[1:] - x[:-1])

y[1] - y[0]

y[2] - y[1]

dy/dx = 2x

results matching ""

    No results matching ""