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):
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 standardizationComparison operators (elementwise comparison):
a > b # elementwise greater-than a < b # elementwise less-than a == b # equality a != b # inequalityLogical operators (elementwise logical operations):
(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.