Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Writing Vectorized Functions

00:00 In the previous lesson, I showed you how to build a graph with Matplotlib based on your NumPy data. This lesson begins the last of our four examples, which is around vector operations on NumPy data.

00:12 In the previous lessons, you saw me multiply a NumPy array with a single value. When you do this, the operation you invoked gets run on each item in the array.

00:22 This is significantly faster than doing the equivalent through the construction of a Python loop. It stays within NumPy’s library, which is optimized for speed.

00:30 Let’s go into the REPL and do a little more with these kinds of operations. Sing it along with me. Second verse, same as the first. To demonstrate vector operations.

00:44 I’m going to use a copy of the data generated in the previous lesson. It’s essentially our resulting portfolio data, which I’ve written out to a CSV file.

00:57 This is the structured data for the portfolio array,

01:08 and now I’ve loaded the data from full_portfolio.csv. Nothing here you haven’t seen before. There’s the result. I can use square brackets to get at a column.

01:23 This is the price info for Friday. Now, to apply an operation.

01:30 When you multiply a column by a single value, you get a new array, which contains each of the values from the previous column multiplied in this case by 123.

01:39 This is the simplest form of operation. It’s called a vector operation because it’s working like a mathematical vector where the array contains the vector and the multiplication is a scalar times a vector, in this case. NumPy can do more than just scalar operations, though. It can also do math on two different vectors.

02:02 This is the result of the Friday prices subtracted from Monday’s prices, which gives you the gain or loss for the week. Looks like I’m down about a buck 80, so it goes.

02:13 If you’re quoting along with me, don’t close your REPL. You’ll want this data in the next lesson. Now, you’ve seen the basics, but what if you want to do something more complicated?

02:23 Next up, how to write functions that can do vector math.

Become a Member to join the conversation.