Vectorized Syntax

What is vectorized syntax in NumPy and pandas?

Answer

Instead of calling ufuncs directly, NumPy and pandas allow many operations to be written using a simpler, cleaner vectorized syntax (syntactic sugar). These operators, as we know, work elementwise and often rely on broadcasting.

  • Arithmetic operators (elementwise math):

    Python
    a = a + b or a += b         # vectorized addition
    a - b                       # subtraction
    a * b                       # multiplication
    a / b                       # division
    
    # broadcasting example
    df = (df - np.mean(df)) / np.std(df)  # elementwise standardization
  • Comparison operators (elementwise comparison):

    Python
    a > b        # elementwise greater-than
    a < b        # elementwise less-than
    a == b       # equality
    a != b       # inequality
  • Logical operators (elementwise logical operations):

    Python
    (a > 10) & (a < 20)    # logical AND
    (a < 5) | (a == 10)    # logical OR
    ~(a > 10)              # logical NOT
Notes and comments

Comment 1: For logical operations, in NumPy and Pandas, we do not use and, or, not. Instead we use the bitwise operators &, |, and ~.

Comment 2: We see that the last two (comparison, logical) allow the masking syntax to work in NumPy and Pandas.

Back to collection