NumPy arrays की ताकत

Efficient Python Code लिखना

Logan Thomas

Scientific Software Technical Trainer, Enthought

NumPy array अवलोकन

  • Python lists का विकल्प
nums_list = list(range(5))
[0, 1, 2, 3, 4]
import numpy as np

nums_np = np.array(range(5))
array([0, 1, 2, 3, 4])
Efficient Python Code लिखना
# NumPy array की समानता
nums_np_ints = np.array([1, 2, 3])
array([1, 2, 3])
nums_np_ints.dtype
dtype('int64')
nums_np_floats = np.array([1, 2.5, 3])
array([1. , 2.5, 3. ])
nums_np_floats.dtype
dtype('float64')
Efficient Python Code लिखना

NumPy array broadcasting

  • Python lists broadcasting सपोर्ट नहीं करतीं
nums = [-2, -1, 0, 1, 2]
nums ** 2
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
Efficient Python Code लिखना
  • List तरीका
# For loop (अप्रभावी विकल्प)
sqrd_nums = []
for num in nums:
    sqrd_nums.append(num ** 2)
print(sqrd_nums)
[4, 1, 0, 1, 4]
# List comprehension (बेहतर, पर सबसे अच्छा नहीं)
sqrd_nums  = [num ** 2 for num in nums]

print(sqrd_nums)
[4, 1, 0, 1, 4]
Efficient Python Code लिखना

NumPy array broadcasting

  • NumPy array broadcasting सबसे आसान!
nums_np = np.array([-2, -1, 0, 1, 2])
nums_np ** 2
array([4, 1, 0, 1, 4])
Efficient Python Code लिखना

बेसिक 1-D indexing (lists)

nums = [-2, -1, 0, 1, 2]
nums[2]
0
nums[-1]
2
nums[1:4]
[-1, 0, 1]

बेसिक 1-D indexing (arrays)

nums_np = np.array(nums)
nums_np[2]
0
nums_np[-1]
2
nums_np[1:4]
array([-1, 0, 1])
Efficient Python Code लिखना
# 2-D list
nums2 = [ [1, 2, 3],
          [4, 5, 6] ]

  • बेसिक 2-D indexing (lists)
nums2[0][1]
2
[row[0] for row in nums2]
[1, 4]
# 2-D array

nums2_np = np.array(nums2)

  • बेसिक 2-D indexing (arrays)
nums2_np[0,1]
2
nums2_np[:,0]
array([1, 4])
Efficient Python Code लिखना

NumPy array boolean indexing

nums = [-2, -1, 0, 1, 2]
nums_np =  np.array(nums)
  • Boolean indexing
nums_np > 0
array([False, False, False,  True,  True])
nums_np[nums_np > 0]
array([1, 2])
Efficient Python Code लिखना
  • Lists में boolean indexing नहीं होती
# For loop (अप्रभावी विकल्प)
pos = []
for num in nums:
    if num > 0:
        pos.append(num)
print(pos)
[1, 2]
# List comprehension (बेहतर, पर सबसे अच्छा नहीं)
pos = [num for num in nums if num > 0]
print(pos)
[1, 2]
Efficient Python Code लिखना

शक्तिशाली NumPy arrays के साथ अभ्यास करते हैं!

Efficient Python Code लिखना

Preparing Video For Download...