DEV Community

Discussion on: Vectors in Python

Collapse
 
cipharius profile image
Valts Liepiņš • Edited

Doing things from scratch is great for learning, but I think it's worth showcasing how same can be done via numpy, which would be better choice for real world applications:

import numpy as np

# Vector in numpy
height_weight_age = np.asarray([70, 170, 40])
grades = np.asarray([85, 80, 75, 62])

# Vector addition / subtraction
print( np.asarray([1, 2, 3]) + np.asarray([4, 5, 6]) ) # => array([5, 7, 9])
print( np.asarray([5, 7, 9]) - np.asarray([4, 5, 6]) ) # => array([5, 7, 9])

# Componentwise sum
# Without `axis=0`, it would sum all matrix components
print( np.asarray([[1,2], [3,4], [5,6], [7,8]]).sum(axis=0) ) # => array([16, 20])

# Multiplying vector with a number
print( 2 * np.asarray([2, 4, 6]) ) # => array([4, 8, 12])

# Componentwise mean
print( np.asarray([[1,2], [3,4], [5,6]]).mean(axis=0) ) # => array([3., 4.])

# Dot product
print( np.asarray([1, 2, 3]).dot(np.asarray([4, 5, 6])) ) # => 32

# Sum of squares
# Equivalent to dot with self
print( np.asarray([1, 2, 3]).dot(np.asarray([1, 2, 3])) ) # => 14

# Magnitude
print( np.linalg.norm(np.asarray([3, 4])) ) # => 5.0

# Squared difference
def squared_difference(v, w):
  return (v - w).dot(v - w)

# Euclidean distance
def distance(v, w):
  return np.linalg.norm(v - w)
Enter fullscreen mode Exit fullscreen mode

Even if some of the cases might look more confusing, greatest advantage of numpy is that it's optimized for maniuplating with large, multidimensional data arrays, which is perfect for data analytics use.

Collapse
 
paulapivat profile image
Paul Apivat

Absolutely agree. Thank you for sharing this!