The post How To Use Numpy Tile appeared first on Sharp Sight.

]]>Without getting into any of the details yet, let me explain what NumPy tile does.

At a very high level, the NumPy tile function creates a new NumPy array by repeating the input array.

However, the exact details of how the function works and what it does are a little more complicated.

Having said that, this tutorial will cover several different topics to help you learn how to use np.tile properly. It will provide you with a quick review of NumPy arrays. It will explain the syntax of np.tile. After showing you the syntax, it will show you step-by-step examples.

**Contents:**

- A quick review of NumPy arrays
- Introduction to NumPy tile
- The syntax of np.tile
- NumPy tile examples
- NumPy tile FAQ

If you’re in a hurry, you can click on any of the links above and it will take you to the appropriate location in the tutorial.

Ok … let’s start the tutorial with a quick review of NumPy.

NumPy is a very commonly used tool for doing data manipulation in Python.

More specifically, NumPy provides a toolkit for working with numbers in Python.

The NumPy package essentially provides tools for organizing and manipulating numbers.

The heart of NumPy is what we call a NumPy array. A NumPy array is just a special Python object for storing numbers in a row-and-column format.

The best way to mentally visualize a NumPy array is thinking about a grid of numbers:

Again, NumPy provides a *lot* of tools for creating these arrays. There’s the NumPy zeros function, which creates NumPy arrays that contain all zeros. There’s the NumPy ones function, which creates NumPy arrays that contain all ones. And there’s the NumPy arange function which creates arrays that contain ranges of numbers. Those are just a few examples though.

Many of the other NumPy functions are used for *manipulating* NumPy arrays that already exist.

There are many examples of this, like NumPy reshape, which changes the shape of a NumPy array. In addition to Numpy reshape, NumPy concatenate, NumPy vstack, and NumPy hstack all combine NumPy arrays together, in one way or another.

And then there’s NumPy tile.

We can use the NumPy tile function to create a new NumPy array based on an existing NumPy array. It’s somewhat similar to NumPy repeat, but definitely different.

Let’s talk about exactly what NumPy tile is and why we use it.

Let’s take a closer look at NumPy tile and how it works.

Put simply, the NumPy tile function creates new NumPy arrays that contain little copies of an input array.

The input array is treated like a “tile” …. a little unit that can be copied and repeated into a grid format.

So when we use the NumPy tile function, it’s not repeating the individual elements in the way that NumPy repeat does.

Again, Numpy tile takes the whole input array and copies everything (including the order of the elements) and repeats that whole structure within the output array.

This enables you to do things like copy an entire 2-dimensional NumPy array and repeat it in the output.

It’s possible to copy the input array once (like in the above image).

But you can also copy the array multiple times, like this:

Exactly *how* we tile the array though is determined by how we use the syntax.

That being the case, let’s take a look at how the code for np.tile works.

The syntax of the NumPy tile function is fairly simple, but at the same time, it’s not immediately easy to understand.

Part of that is because you need to “wrap your mind” around how the function works ….

… and the other reason is that the parameter names are often not used.

In any case let’s take a close look at everything.

To call the NumPy tile function, you’ll commonly use the syntax `np.tile()`

.

Keep in mind that this assumes that you’ve imported NumPy with the code `import numpy as np`

. If you instead import NumPy with the code `import numpy`

, you’ll have to refer to the function as `numpy.tile()`

instead. Just remember that how you call the function depends on how you’ve imported NumPy!

(Throughout this explanation of the syntax, I’ll mostly refer to the function as np.tile, but I might alternatively call it numpy.tile. They are both essentially the same.)

So we call the function with the function name `np.tile()`

.

Then inside of the function are two parameters that enable you to control how the function works: `A`

and `reps`

.

Let’s talk about those parameters in more detail.

The np.tile function really only has two parameters:

`A`

`reps`

Let’s talk about them individually.

`A`

(required)The `A`

parameter enables you to specify the input array.

This array will essentially function as the “tile” that gets copied and repeated inside of the output array.

Technically, NumPy will allow you to provide any “array like input” to the `A`

parameter.

In Python, “array like inputs” include:

- NumPy arrays
- Python lists
- Python tuples

No matter what, the output will still be a NumPy array, but np.tile is fairly flexible in terms of the types of inputs that it will operate on.

Note that NumPy requires you to pass something to this parameter. So you must provide an argument to the `A`

parameter.

However, like many parameters in Python functions, you do not explicitly need to type the “A” parameter. This means that you can pass an argument to the `A`

parameter by position. If you do this, the first argument to the function will be treated as the argument to the A parameter. (If this is confusing, look at the examples to see how this works.)

`reps`

The `reps`

parameter enables you to indicate how to repeat the input array.

That includes how many times to repeat it, but also the structure of the tiled output.

To do this, you will pass an integer or an “array like” object to `reps`

.

It will be easiest to understand by looking at examples, but let me quickly explain.

If you provide an integer `n`

to `reps`

, then it will simply copy the array `n`

times, horizontally. So if you set `reps = 2`

, it will produce an output with two instances of the input array, tiled horizontally.

But remember: you can also pass an “array like” object to `reps`

.

That means that you can pass a list or a tuple to `reps`

. When you do, the first number in the tuple is the number of repeats *downwards* and the second number in the tuple is the number of repeats *across*.

And if you have more than two numbers, it will actually repeat into a greater number of dimensions! So you can actually use np.tile to create 3-dimensional or multi dimensional NumPy arrays.

That’s a little more complicated, so we’re not going to cover that …. we’ll stick to 1D and 2D arrays here, for the sake of simplicity.

Ok. Now that you’ve seen how the syntax works, let’s take a look at some proper examples of NumPy tile.

NumPy tile isn’t terribly hard to understand, but it can be a little bit confusing in the beginning.

That’s why we’re going to start with very simple examples and then slowly increase the complexity. In the later examples, you’ll start to get more of a sense of how np.tile works.

**Examples:**

- Tile a list of numbers horizontally
- Tile a 1D NumPy array horizontally
- How to tile an array vertically
- Tile an 1-d input both vertically and horizontally
- Tile a 2-dimensional array vertically and horizontally

One quick note … make sure that you import NumPy properly.

In order for the following examples to work properly, you need to import NumPy with the following code:

import numpy as np

Ok … let’s start with a very simple example.

First, we’re going to repeat a simple Python *list* horizontally.

I’m going to use a list here because I think that it makes the syntax more intuitive if you can actually see the numbers in the input. It makes it easier to directly compare the input to the output.

The input list will contain three numbers: `[6, 7, 8]`

.

We’ll repeat this two times, horizontally. To do this, we’ll set `reps = 2`

.

Ok. Let’s take a look at the code.

np.tile(A = [6,7,8], reps = 2)

This creates the following NumPy array as an output:

array([6, 7, 8, 6, 7, 8])

As you can see, the output array contains the original input numbers – 6, 7, and 8 – repeated two times.

But notice *how* they are repeated.

The elements of the input are __not__ repeated individually, such that the first element is repeated two times and *then* the second element is repeated two times (i.e., `[6, 6, 7, 7, 8, 8]`

). That’s how the NumPy repeat would repeat the input.

No. NumPy tile repeats the input as if it is copying the original input as a coherent unit, including the original order of the elements.

The input array (in this case, a list) is treated like a small ’tile’ that can be copied and repeated.

Here, because we’ve set `reps = 2`

, it only copied the array one extra time … meaning the total number of repeated ’tiles’ is 2.

Notice one thing.

NumPy tile copied the array *horizontally*. This is the default behavior if you only provide an integer as the argument to the `reps`

parameter. It just tiles the input horizontally.

That will change though when we look at more complex examples, with an array of numbers as the argument to reps. We’ll see that in future examples.

Very quickly, I want to re-do example 1 with a proper NumPy array as an input instead of a list.

Recall that in example 1, we ran the code with a *list* as the input.

Also remember that NumPy tile will accept any *array like input* as the argument to the `A =`

parameter. So it will accept a list, a tuple, or a NumPy array.

To reinforce this point, let’s redo the example with a NumPy array.

First, let’s just create a simple NumPy array:

simple_array = np.array([6,7,8])

If you print this out, with `print(simple_array)`

, you’ll see that it contains the same elements as the list in example 1: `[6 7 8]`

. However, if you check the data type with the code `type(simple_array)`

, you’ll see that `simple_array`

is an `numpy.ndarray`

… i.e., a NumPy array.

Ok. We have our NumPy array. Let’s use np.tile.

np.tile(A = simple_array, reps = 2)

OUT:

array([6, 7, 8, 6, 7, 8])

As you can see, the array of input numbers – 6, 7, and 8 – have been tiled across.

This code is effectively the same as `np.tile(A = [6,7,8], reps = 2)`

. The only difference in this case is that we’re using a proper NumPy array as the input instead of a list.

Again, I’m showing you this to reinforce the point that the np.tile function will operate on a variety of array like inputs.

In this example, we’re going to take a simple 1-dimensional input and tile it *downwards*.

Essentially, we’re going to treat the input like a row of data, and *copy the row*.

To keep things simple, we’re going to use a Python list here as the input, but remember that this could also be a NumPy array.

Ok … let’s take a look at the code.

np.tile(A = [6,7,8], reps = (2,1))

OUT:

array([[6, 7, 8], [6, 7, 8]])

So what happened here?

Effectively, np.tile just cloned the row. But why?

Look carefully at the code we used to execute this: `np.tile(A = [6,7,8], reps = (2,1))`

.

Specifically, look at the `reps`

parameter.

We used the code `reps = (2,1))`

.

This tells NumPy how many times to “repeat” the input “tile” downwards and across.

So when we type `reps = (2,1))`

, we’re indicating that in the output, we want 2 tiles going downward and 1 tile going across (including the original tile). This will essentially just duplicate the original input downward.

The argument to reps – the tuple of numbers – tells np.tile how many times to tile the input array.

Ok … now we’re going to make things a little more complicated.

We’re going to tile a 1-dimensional input both vertically and horizontally.

To keep things simple, we’ll use a Python list as the input, but remember again that we could use use a NumPy array as an input.

Here, we’re going to use a *very* simple input. Only two numbers in a list: `[6, 7]`

.

And we’re going to tile this list of numbers three times downwards and two times across.

To do this, we’ll set `reps = [3,2]`

.

If we’re treating the input list `[6,7]`

as a “tile”, then the output will be like a 3×2 grid of those tiles.

Let’s look at the full code:

np.tile(A = [6,7], reps = [3,2])

Which produces the following NumPy array as an output:

array([[6, 7, 6, 7], [6, 7, 6, 7], [6, 7, 6, 7]])

If you carefully read example 1, example 2, and example 3, then you should probably understand this, but let me explain.

We’re treating the input list `[6,7]`

as a “tile” … as a unit that can be copied and repeated.

The `reps`

parameter indicates how many times to repeat it. By setting `reps = [3,2]`

, we’re indicating that we want to repeat the input “tile” three times vertically and two times horizontally.

Ok. One more example.

Here, we’re going to use a 2-dimensional array as an input.

First, let’s just create our 2-dimensional NumPy array using the NumPy array function.

np_array_2d = np.array([[6,7],[8,9]])

And let’s print out the array:

print(np_array_2d)

OUT:

[[6 7] [8 9]]

Essentially, `np_array_2d`

is a 2×2 NumPy array.

Next, we’re going to tile the array with np.tile.

np.tile(np_array_2d, reps = [2,2])

OUT:

array([[6, 7, 6, 7], [8, 9, 8, 9], [6, 7, 6, 7], [8, 9, 8, 9]])

The output here is a NumPy array with 4 rows and 4 columns.

But take a careful look at the contents of the output array. It essentially contains four little copies of the original input: two vertically and two horizontally.

That’s really all np.tile does …. it takes an input array and uses that input as a “tile” that can be copied and repeated multiple times, in a grid format, inside of the output array.

Let’s quickly address some frequently asked questions about NumPy tile.

**Frequently asked questions:**

This is fairly straight forward.

We essentially covered this in example 3.

Let’s assume that you have a 1-dimensional input (a 1D NumPy array or a list).

To duplicate the row, you’ll use np.tile with `reps = [2,1]`

.

np_array_1d = np.array([6,7,8,9]) np.tile(A = np_array_1d, reps = [2,1])

OUT:

array([[6, 7, 8, 9], [6, 7, 8, 9]])

Obviously, you could copy the row more than twice …. to do that you’d just have to change the argument to the `reps`

parameter.

Yep.

In the examples section of this tutorial, we stuck to 1D inputs and 2D inputs, for the sake of simplicity.

Also, we only tiled those inputs into 1 or 2 dimensions.

However, you can actually use np.tile in higher dimensions.

For example:

np.tile(A = [6,7], reps = [2,2,2])

OUT:

array([[[6, 7, 6, 7], [6, 7, 6, 7]], [[6, 7, 6, 7], [6, 7, 6, 7]]])

To be honest, it’s a little more complicated to visualize and think about higher dimensions, so for the sake of simplicity, I’m not going to explain much about this.

Just understand that np.tile *does* work in more than 2 dimensions.

In this tutorial, I’ve explained how np.tile works in a fair amount of detail.

But np.tile is just one function in the larger NumPy system.

To really be able to use NumPy fluently, you’ll need to learn:

- How to use the NumPy array function
- What NumPy axes are, and how NumPy axes work
- How to summarize NumPy arrays
- How to reshape NumPy arrays

There’s quite a bit to learn!

Moreover, there’s a lot more to learn about other parts of the Python data science stack, like matplotlib, Pandas, and sci-kit learn.

If you want to learn the Python data science stack, then sign up for our email list.

Here at Sharp Sight, we regularly publish tutorials about:

- NumPy
- Pandas
- Base Python
- Scikit learn
- Machine learning
- Deep learning
- … and more.

When you sign up for our email list, you’ll get our tutorials delivered directly to your inbox.

Ready to learn more data science?

Sign up now.

The post How To Use Numpy Tile appeared first on Sharp Sight.

]]>The post How to use numpy repeat appeared first on Sharp Sight.

]]>The NumPy repeat function essentially *repeats* the numbers inside of an array. It repeats the individual *elements* of an array.

Having said that, the behavior of NumPy repeat is a little hard to understand sometimes. It’s a little un-intuitive.

To help explain how this function works, I’m going to explain everything step by step. I’ll review the basics of NumPy arrays and how they are structured. Then I’ll explain the NumPy repeat function. Next, I’ll explain the actual syntax of np.repeat, before moving on to some examples and questions.

**Table of Contents:**

- A quick review of NumPy arrays
- Introduction to NumPy repeat
- The syntax of np.repeat
- NumPy repeat examples
- NumPy repeat FAQ

You can click on any of the above links and it will take you to the appropriate section in the tutorial.

But if you really want to understand how this works, I recommend that you read the full tutorial.

Ok. Onward.

First, let’s just review NumPy arrays.

A NumPy array is just an array of numbers that we create with the NumPy package. It’s basically a special kind of object in Python that we use to store and manipulate numeric data.

NumPy arrays can be 1-dimensional:

… 2-dimensional:

Or even have 3 or more dimensions.

The real constraint with NumPy arrays is that they essentially can only hold numbers.

You can think of NumPy arrays like vectors, matrices, and tensors in mathematics.

Importantly, NumPy arrays have “axes.”

What are axes?

You can think of axes like directions.

A 1-dimensional array only has one axis, called axis-0:

And 2-dimensional arrays have two axes, called axis-0 and axis-1:

As it turns out, NumPy axes are important because they are often used when we manipulate arrays.

We’ll actually use NumPy axes when we manipulate our NumPy arrays with NumPy repeat.

Now that we’ve reviewed NumPy arrays, let’s talk more specifically about the NumPy repeat function.

Essentially, the NumPy repeat function repeats the elements of an array.

That’s basically all it does!

It can get a little more complicated though in more complicated cases.

One important thing to understand is that by default, NumPy repeat will flatten out an array.

That might not make sense, so let me give you an example. Let’s say that you have a 2-dimensional array with some numbers.

If you apply the np.repeat function on the 2-dimensional input array, then by default, it will repeat the values and put those repeated values into a 1-dimensional array.

By default, the output will be 1-dimensional.

It’s possible to change that behavior, but to do so, you need to understand the syntax of np.repeat.

That being said, let’s take a look at the syntax.

The syntax of the np.repeat function is fairly straightforward.

First of all, you will typically call the function with the name `np.repeat()`

.

However, it’s important to note that how exactly you call the function depends on how you’ve imported NumPy.

Remember that before you *use* NumPy in a Python program, you need to *import* NumPy.

The common way to do this is with the code `import numpy as np`

. That’s a very common convention used by many programmers.

When you import NumPy with the alias “`np`

,” it allows you to refer to the NumPy package with the prefix “`np.`

” in your syntax.

So if you import NumPy with the code `import numpy as np`

, then you will call the repeat function as `np.repeat()`

.

On the other hand, if you instead import NumPy with the code `import numpy`

, you’ll have to use the prefix “`numpy.`

” in your syntax, which means that you’d have to call the function as `numpy.repeat()`

.

Essentially, how you call the function depends on how you import NumPy.

Having said that, I’ll mostly refer to the function as `np.repeat()`

, but you might see me use the term `numpy.repeat()`

as well.

Let’s finally take a close look at the syntax of np.repeat.

First, you’ll typically call the function with the name `np.repeat()`

.

Then inside of the function are a set of parameters that you can use to specify exactly how the function will work.

The parameters are important, so let’s take a look at them.

The np.repeat function has 3 parameters:

`a`

`repeats`

`axis`

Let’s examine each of these individually.

`a`

(required)The `a`

parameter enables you to specify the “array” that you will use as the input to np.repeat.

Keep in mind that although the np.repeat function is primarily designed to operate on NumPy arrays, it will also work on any array-like object. That includes Python lists and Python tuples. Technically, it will even operate on a string (although it will treat it like a Python list). The important thing to understand is that np.repeat is flexible concerning what inputs it will work on.

Also keep in mind that the `a`

parameter is required. This means that you *must* provide some sort of input to the function.

`repeats`

(required)The `repeats`

parameter enables you to specify how many times to repeat the items in the input array.

The argument to this parameter will be an integer …

… so if you want to repeat each item twice, you’ll type ‘`2`

‘.

… if you want to repeat each item three times, you’ll type ‘`3`

‘.

… etcetera.

This is fairly self explanatory, but you’ll be able to see how this works in practice in the examples section of the tutorial.

`axis`

Finally, the `axis`

parameter enables you to specify the axis along which you will repeat the elements.

This is a little confusing to NumPy beginners, because most people don’t really understand what axes are.

Remember, NumPy arrays have axes. A 1D NumPy array has one axis, and a 2D array has two axes.

These “axes” are essentially like *directions*.

When we use the `axis`

parameter, we are specifying the direction along which we will repeat the items.

So for example, if we have a 2-dimensional NumPy array and we want to repeat the items downwards down the columns, we will set `axis = 0`

.

If we want to repeat the items horizontally across the rows, we will set `axis = 1`

.

(Although, keep in mind that the axis specifications will be different for a 1-dimensional array.)

Again, this might not make a lot of sense. If you’re confused about NumPy axes, make sure to read our tutorial that explains what a NumPy axis is.

You should also pay close attention to example 4 and example 5 in this tutorial which explain how to repeat elements down the columns or across the rows of a 2D array.

Finally, let’s talk about the output of np.repeat.

This is simple.

The output of NumPy repeat is a NumPy array.

But keep in mind that the size and exact shape of the output will depend on how we use the np.repeat function.

Now that I’ve explained the syntax, let’s look at some examples of how to use NumPy repeat.

**Examples:**

- Repeat a single number
- How to repeat a 1-d list of numbers multiple times
- How to repeat the values of a 2-d array
- Repeat elements down the columns
- Repeat elements across the rows

One quick note before you run any code:

You need to import NumPy properly.

I’m assuming here that you have NumPy already *installed* on your machine (if you don’t, you should install Anaconda, which will include NumPy).

But even if you have NumPy installed on your computer, you will need to import it into your working environment by using the following code:

import numpy as np

This essentially makes the NumPy functions available in our code by typing the prefix “np.” followed by the name of the function.

Ok. With that out of the way, let’s look at some examples.

First, let’s start veeeery simple.

Here, we’re just going to repeat a single number several times.

To do this, we’ll call the np.repeat function. Inside of the parenthesis, we’ll provide the value that we want to repeat with the `a =`

parameter, and specify the number of repeats with the `repeats =`

parameter.

Essentially, we’re going to repeat the number “7” four times.

Here’s the code:

np.repeat(a = 7, repeats = 4)

Which produces the following output:

array([7, 7, 7, 7])

This is really easy to understand.

We indicate that we will repeat the number ‘7’ with the `a`

parameter, and indicate that we will repeat it four times with the `repeats`

parameter.

Notice also that the output is a NumPy array. If you want, you could check that with the code `type(np.repeat(a = 7, repeats = 4))`

.

Very quickly, let’s redo the above examples *without* explicitly referencing the parameter names.

For better or for worse, many Python programmers write their code without explicitly showing the parameter names.

Personally, I think this is a bad habit (one that I’ve been guilty of myself). It’s much more clear to explicitly show the parameter names.

But just so you can see it, let’s run the code without the parameter names. We’ll just pass arguments to the function by position.

np.repeat(7, 4)

OUT:

array([7, 7, 7, 7])

The output is still the same.

The only difference is that we’ve removed the actual parameters. Python knows that the argument in the first position refers to the “`a`

” parameter and the item in the second position refers to the “`repeats`

” parameter.

The code looks a little different, but it’s essentially the same and the output is the same.

Again, I want you to see this so you understand what’s going on when the parameter names are removed.

Now, we’re going to move on to a slightly more complicated example.

Instead of repeating a single number, we’re going to repeat *multiple* numbers.

This example is almost exactly the same as the first example, except we’re going to make one small modification to our code.

… we’re going to provide a *list* of numbers to the `a`

parameter.

Let’s take a look.

Here, we’re going to repeat the numbers 6 and 7 two times each. We specify the two numbers to repeat with the code `a = [6,7]`

. Then the parameter `repeats = 2`

indicates that we’ll repeat those numbers two times.

np.repeat(a = [6,7], repeats = 2)

OUT:

array([6, 6, 7, 7])

Notice what happened here.

Our input numbers, 6 and 7, are repeated two times each.

And notice *how* it repeats the numbers. It repeats the first number two times and then repeats the second number two times.

The output is a NumPy array, as we should expect, but it’s a 1-dimensional NumPy array.

This is important!

By default, the output of numpy.repeat is a flat, 1-dimensional array that simply repeats all of the elements of the input.

We’ll see this behavior in the next example as well, and we’ll only be able to change it when we finally start to use the `axis`

parameter.

In this example, we’re going to use a 2-d array as the input to NumPy repeat.

First, let’s create a NumPy array.

Here, we’re going to use the NumPy array function to create a 2-dimensional array with four numbers.

np_array_2d = np.array([[6,7],[8,9]])

We can print this out with the code `print(np_array_2d)`

which produces the following output:

[[6 7] [8 9]]

The resulting NumPy array, `np_array_2d`

, is basically an array with 2 rows and two columns.

Now, we’re going to use np.repeat to repeat the elements of the array.

Here’s the code:

np.repeat(a = np_array_2d, repeats = 2)

OUT:

array([6, 6, 7, 7, 8, 8, 9, 9])

This example is actually easy to understand if you understood example 1 and example 2.

The array `np_array_2d`

is the input to the function. We’re using the `repeats`

parameter to specify that we want to repeat every element of the input two times.

When it executes, the np.array function simply takes every individual element of the input, repeats it 2 times, and puts it into a 1-dimensional output array.

Now, let’s make things more complicated.

We’re going to work with a 2-dimensional NumPy array again.

But we’re now going to use numpy.repeat to repeat the values downward down each column.

This is a little more complicated and more difficult to understand, so let’s take it step by step.

First let’s just create a 2-d NumPy array.

This is the same as the array in the previous example, so if you already ran that code, you don’t need to run this again.

np_array_2d = np.array([[6,7],[8,9]])

If we print this out with the code `print(np_array_2d)`

, you can see that it’s a 2×2 array with four values:

[[6 7] [8 9]]

Now, we’re going to repeat the values of each column *downward* down each column.

Let’s first run the code and then let me explain.

Here, we’re going to run np.repeat with 2 repeats. But we’re now going to use the `axis`

parameter.

np.repeat(a = np_array_2d, repeats = 2, axis = 0)

OUT:

array([[6, 7], [6, 7], [8, 9], [8, 9]])

So look at what happened …

The np.repeat function repeated the values of each column *downward*.

Why?

To understand this, you need to understand NumPy axes.

Remember that NumPy arrays have axes. The axes of an array are like *directions*. For a 2-dimensional array, axis-0 is the axis that points downwards down the columns and axis-1 is the axis that points horizontally across the rows.

When we use numpy.repeat with `axis = 0`

, we’re telling numpy.repeat to operate in the axis-0 direction.

So when we set `axis = 0`

, it takes the values of the array and it repeats them *in that direction*. Remember, axis-0 points downwards down the columns. So in this case, it repeats the values downwards down the columns.

The behavior of np.repeat actually makes sense, but to really understand this, you really need to understand NumPy array axes first. So if you’re a little confused by this example, you might want to read our tutorial about NumPy axes.

Next, let’s do something similar to the last example. In the previous example, we repeated elements down the columns.

In this example, we will repeat elements *horizontally across the rows*.

This is very easy to do and it will make sense if you read the previous example.

We’re essentially going to set `axis = 1`

which indicates that we want np.repeat to operate in the axis-1 direction.

Again, let’s create a 2-d NumPy array.

This is the same as the array in the last example, so if you already ran that code, you don’t need to run this again.

np_array_2d = np.array([[6,7],[8,9]])

If we print this out with the code `print(np_array_2d)`

, you can see the contents. It’s a 2-dimensional NumPy array:

[[6 7] [8 9]]

Now, let’s repeat those values horizontally.

To do this, we’ll use np.repeat with `axis = 1`

.

np.repeat(a = np_array_2d, repeats = 2, axis = 1)

And here’s the output:

array([[6, 6, 7, 7], [8, 8, 9, 9]])

This is very similar to the previous example where we repeated values downward.

But here, by setting `axis = 1`

, we’re telling np.repeat that we want to repeat the values in the axis-1 direction. Remember, for a 2-dimensional array, axis-1 is the direction that points horizontally across the rows.

So essentially, this code will take each element in the input array and repeat it horizontally across axis-1.

Again, this is fairly easy to understand once you really understand NumPy axes. To learn more about axes, read our tutorial that explains what a NumPy axis is and how we use them.

Now let’s address some frequently asked questions about NumPy repeat.

**Frequently asked questions:**

- How can I duplicate the rows of a 2-D array?
- How can I duplicate a 1-dimensional array?
- What is the difference between np.repeat and np.tile?

If you already have a 2-dimensional NumPy array, then it’s relatively easy to duplicate all of the rows.

To do this, we’re simply going to use np.repeat with `axis = 0`

.

Let me show you.

First, we’ll just create a 2D numpy array:

np_array_2d = np.array([[1,2,3],[4,5,6]])

Now, let’s duplicate the rows with NumPy repeat:

np.repeat(a = np_array_2d, repeats = 2, axis = 0)

OUT:

array([[1, 2, 3], [1, 2, 3], [4, 5, 6], [4, 5, 6]])

As you can see, np.repeat has produced an output array that repeats every row of the input.

Note that this is essentially the same as example 4 in the examples section of this tutorial.

Duplicating a 1D array is a little harder because a 1-dimensional array only has one axis (axis 0).

This is a problem, because when we duplicate the rows, there needs to be another dimension in which to copy the rows.

So essentially, to do this, we actually need to increase the number of dimensions of the array first, and then copy the row.

Let’s take a look.

First, let’s just create a 1-dimensional NumPy array.

np_array_1d = np.array([1,2,3,4])

If you were to use np.repeat on this with `axis = 1`

, then you’d get an error.

So before we run that code, we need to expand the number of dimensions.

np_array_2d = np.expand_dims(np_array_1d, axis = 0)

And let’s print this out so you can see it.

print(np_array_2d)

OUT:

[[1 2 3 4]]

Now, let’s duplicate the row.

np.repeat(a = np_array_2d, repeats = 2, axis = 0)

OUT:

array([[1, 2, 3, 4], [1, 2, 3, 4]])

As you can see, the output of np.repeat in this case is a new array with the row duplicated two times.

The np.repeat function repeats the individual *elements* of an input array.

But np.tile will take the entire array – including the order of the individual elements – and copy it in a particular direction.

So the difference is between copying the individual numbers verses copying the whole array all at once.

To learn more about np.tile, check out our tutorial about NumPy tile.

In this tutorial, we’ve strictly focused on the NumPy repeat function.

But if you’re serious about doing data manipulation in Python (i.e., for machine learning and deep learning), you really need to know more.

I recommend that you learn about:

- How to create NumPy arrays with np.arange
- How to change the shape of a NumPy arrays
- Appending new elements to a NumPy array
- How to concatenate NumPy arrays together

You’ll also want to learn about summary functions like np.sum, np.median, etc.

Moreover, even after you learn NumPy, you will probably need to learn a little about Pandas and matplotlib.

If you’re serious about learning NumPy (and Pandas, and matplotlib), then we can help.

Here at Sharp Sight, we teach data science.

We can show you how to do data manipulation, data visualization, data analysis, and machine learning in Python.

Want to learn more?

Sign up right now for our email list.

Members of our email list get immediate access to our free tutorials.

When you sign up, you’ll get free tutorials on:

- NumPy
- Pandas
- Base Python
- Scikit learn
- Machine learning
- Deep learning
- … and more.

You’ll also get exclusive notifications when we open our premium data science courses for enrollment.

Want to learn data science?

Then sign up right now for our email list.

The post How to use numpy repeat appeared first on Sharp Sight.

]]>The post Numpy square root explained appeared first on Sharp Sight.

]]>This is a fairly easy NumPy function to understand and use, but for the sake of helping true beginners, this tutorial will break everything down. I’ll quickly review NumPy, I’ll explain the syntax, and I’ll show you some examples.

That being said, if you’re in a hurry, you can click on one of the links to the following sections and get what you’re looking for.

**Contents:**

- A quick review of NumPy
- Introduction to NumPy square root
- The syntax of np.sqrt
- NumPy square root examples
- NumPy square root FAQ

If you’re a real beginner or you have some time on your hands, I recommend that you read the whole tutorial. Everything will make more sense that way.

But if you’re in a hurry, click on one of the links in the Contents list, and it will take you directly to the appropriate section of the tutorial.

Ok … before we get into the Numpy square root function itself, let’s start with a quick review of NumPy.

The NumPy square root function is part of the NumPy module.

So what is NumPy?

NumPy is a toolkit for performing computing with numeric data in Python.

Base Python itself has many functions for working with numeric data, but Numpy has been carefully designed to work with large *arrays* of numbers.

What is a Numpy array?

A Numpy array is just a special data structure for storing numbers. You can think of a Numpy array as a grid of numbers.

In simple cases, these arrays can be 1-dimensional:

In more complicated cases, Numpy arrays can be 2-dimensional:

Numpy also supports 3D arrays, and higher dimensional arrays.

So what makes NumPy important is that it provides a variety of tools for creating arrays of numbers, manipulating those arrays, and performing mathematical computations on those arrays.

One tool for performing calculations on a NumPy array is the NumPy square root function.

So what does numpy.sqrt do?

To put it simply, the NumPy square root function calculates the square root of input values.

So if you give it an input , `numpy.sqrt()`

will calculate :

Critically though, the Numpy square root function also works on Numpy arrays.

So if you give it a Numpy array as an input, Numpy square root will calculate the square root of every value in the array.

I’ll show you examples of both cases in the examples section, but first let’s take closer look at the syntax.

The syntax of NumPy square root is extremely simple. It’s probably one of the simplest functions in the NumPy module.

To call the function, you just call it by name (although exactly how you call it depends on how you’ve imported NumPy).

When you initially import NumPy into your environment, you can simply do this with the code `import numpy`

. This will enable you to call NumPy functions with the prefix “`numpy.`

” followed by the name of the function.

However, it is very common to give NumPy a “nickname” when it’s imported. It’s very common to import NumPy with the code `import numpy as np`

. This essentially gives NumPy the alias `np`

in your code, which enables you to use “`np.`

” instead of “`numpy.`

” when you call functions.

This is important, because how you import numpy will determine how you call it in your code.

Since it’s common to import NumPy with the `code import numpy as np`

, we’ll follow that convention in our syntax.

Just be aware though that `np.sqrt()`

and `numpy.sqrt()`

are essentially interchangeable, as long as you’ve imported NumPy the correct way, respectively.

Assuming that we’ve imported NumPy with the code `import numpy as np`

, we call call the NumPy square root function with the code `np.sqrt()`

.

Then inside of the function, there is a parameter that enables you to specify the input of the function.

Let’s quickly discuss this.

The NumPy square root function actually has two parameters, but we’re really only going to talk about one of them.

**Parameters:**

`x`

`out`

Let me quickly explain each of these separately.

`x`

(required)The `x`

parameter enables you to specify the input to the np.sqrt function.

Technically, the `x`

parameter enables you to specify the radicand. The radicand is the value under the radical when you compute the square root.

Keep in mind that the function is somewhat flexible in what types of inputs it will accept as arguments to the `x`

parameter. You can provide a single number, but you can also provide a NumPy array or any array-like input. The array-like inputs that will work are things like Python lists and tuples.

If you provide a NumPy array or array-like input, numpy.sqrt will compute the square root of *each value in the array*.

I’ll show you examples of all of these cases in the examples section.

Note that you *need* to provide an argument to the `x`

parameter, meaning that you need to provide *some* sort of input to the function … an integer, an array, a list. You need to provide something as an input.

`out`

The `out`

parameter enables you to specify an array where the output will be stored.

This parameter is not commonly used by beginners, so we’re not really going to work with it in this tutorial.

Ok, now that I’ve explained the syntax and the parameters, let’s take a look at some examples.

As I mentioned earlier, Numpy square root is very easy to use.

Having said that, I’m still going to start with the simplest possible example, and then increase the complexity as we move on to other examples.

**Examples:**

- Use np.sqrt on a single number
- Use np.sqrt with a 1-dimensional array
- Using np.sqrt with a 2-dimensional array

One quick note.

As I mentioned earlier, you’ll need to import NumPy into your environment in order for the code to work properly.

You can do that by running this code:

import numpy as np

This imports the NumPy module with the alias “`np`

“. As I mentioned previously, this is a common convention among NumPy users. Ultimately, it enables us to refer to NumPy as `np`

in our code, so the prefix “`np.`

” will be in front of the function name when we call a function.

First, let’s start simple.

Here, we’re going to apply the NumPy square root function to a single numeric input.

np.sqrt(9)

OUT:

3.0

So what happened here?

We called the function with the code `np.sqrt(9)`

. This is essentially the same as `np.sqrt(x = 9)`

, but we can chose not to explicitly type the `x =`

. The code works the same way in either case.

And what did it compute?

This is very simple.

Here, np.sqrt computed the square root:

As I’m sure you know, , so it gave us the output of 3.0.

Next, let’s use the function on a 1-dimensional “array” of numbers.

Actually, for the sake of clarity, I’m going to show you the example with a Python list.

Remember: numpy.sqrt will operate on any array-like structure.

I think that Python lists are a little easier to understand, because they make the syntax easier to understand. For the sake of completeness though, I’ll re-do this example later with a proper NumPy array.

Ok, let’s run the code. Here, we’re going to apply the np.sqrt function to the Python list `[0,1,2,3,4]`

.

np.sqrt([0,1,2,3,4])

Which produces the following output:

array([0. , 1. , 1.41421356 , 1.73205081 , 2. ])

So what happened here?

This is really simple.

Remember: when we apply np.sqrt to a list, it computes the square root for every element of the list.

So it takes the input values `[0,1,2,3,4]`

, computes the square root for each value, and produces the output in the form of a NumPy array.

That’s it!

Very quickly, let’s redo this example with a proper NumPy array as the input.

So, instead of using the list `[0,1,2,3,4]`

, we’re going to use a NumPy array that contains those values instead.

Let’s first create the array:

np_array_1d = np.arange(5)

If you print this out, you’ll see the contents:

print(np_array_1d)

OUT:

[0 1 2 3 4]

So `np_array_1d`

contains the same values as the list that we worked with earlier, but it’s in the form of a NumPy array. Note that you can check the object type with the code `type(np_array_1d)`

… which will show you that it’s a `numpy.ndarray`

.

Ok. So we now have our NumPy array, `np_array_1d`

.

Now, let’s use that as the input to `np.sqrt()`

:

np.sqrt(np_array_1d)

Which produces the output:

array([0. , 1. , 1.41421356 , 1.73205081 , 2. ])

Notice that this is the same output that we got for `np.sqrt([0,1,2,3,4])`

.

The point that I’m trying to make here is that np.sqrt will operate on either a list or a NumPy array … in fact, it will work on any array-like object.

Next, we’re going to use np.sqrt on a 2-dimensional array.

First, let’s just create the array.

np_array_2d = np.arange(10).reshape([2,5])

This new array, `np_array_2d`

, is a simple 2-dimensional array. It contains the numbers from 0 to 9, arranged in an array with 2 rows and 5 columns. We’re creating this array with the np.arange function, in conjunction with the NumPy reshape method.

You could print it out with `print(np_array_2d)`

, but visually, it looks like this:

Now, let’s use this array as the input to np.sqrt:

np.sqrt(np_array_2d)

Which produces the following output:

array([[0. , 1. , 1.41421356, 1.73205081, 2. ], [2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ]])

This is really easy to understand, if you’ve been paying attention to the previous examples.

When we use a 2D NumPy array as the input, the np.sqrt function simply calculates the square root of every element of the array.

The output of the function is simply an array of those calculated square roots, arranged in exactly the same shape as the input array. So if the input array has 2 rows and 5 columns … then the output array will have 2 rows and 5 columns.

So far, I’ve shown you examples of how the NumPy square root function operates on scalars, 1D arrays, and 2D arrays.

But keep in mind that it will also work on arrays of different sizes and shapes.

So you can apply this function to 3D arrays or higher-dimensional arrays and it works in essentially the same way: it computes the square root of each element.

Let’s quickly take a look at one commonly asked question about NumPy square root.

**Frequently asked questions:**

Not exactly.

Taking the square root of -1 with np.sqrt causes an warning message:

np.sqrt(-1)

RuntimeWarning: invalid value encountered in sqrt Out: nan

Essentially, NumPy is saying that the input is invalid. The code still runs, but the output is “nan” … meaning “not a number.”

Having said that, NumPy supports complex numbers, and the np sqrt function *does* operate on complex numbers.

np.sqrt(-1+0j)

OUT:

1j

Explaining this example is a little complex (heh heh), and it’s outside the scope of this tutorial.

Ultimately, you need to know that NumPy sqrt does not natively operate on negative numbers, and to get it to do so, you’ll need to use complex numbers.

Do you have other questions about NumPy square root?

Leave your question in the comments section below.

If you’re interested in data science in Python, you’ll have a lot to learn … a lot more than just the NumPy square root function.

You’ll need to learn more about NumPy, but also Pandas, matplotlib, and several other packages.

We have plenty of free tutorials here that you can check out.

**NumPy tutorials:**

- NumPy random seed explained
- An explanation of NumPy axes
- How to create a NumPy array filled with zeros
- How to use NumPy linspace
- Creating normally distributed data with np.random.normal

Those are just a few of our NumPy tutorials.

We also have tutorials about Pandas and matplotlib.

Ultimately though, if you want to regularly get our FREE tutorials, you should sign up for our email list.

Members of our email list are notified *immediately* when we publish new data science tutorials … we basically send the tutorials to your inbox.

If you sign up, you’ll get free tutorials on a variety of data science topics:

- NumPy
- Pandas
- Base Python
- Scikit learn
- Machine learning
- Deep learning
- data science in Python
- data science in R
- … and more.

So if you want access to our free tutorials, sign up right now:

The post Numpy square root explained appeared first on Sharp Sight.

]]>The post How to use numpy exponential appeared first on Sharp Sight.

]]>This is a very simple function to understand, but it confuses many people because the documentation is a little confusing. It seems particularly confusing for beginners.

With that in mind, this tutorial will carefully explain the numpy.exp function. We’ll start with a quick review of the NumPy module, then explain the syntax of np.exp, and then move on to some examples.

Here are the contents.

**Contents:**

- A quick review of NumPy
- Introduction to NumPy exponential
- The syntax of np.exp
- Examples of NumPy exponential
- NumPy exponential FAQ

You can click on any of the links above, and it will take you to the appropriate spot in the tutorial. So if you have something that you’re trying to quickly understand about numpy.exp, you can just click to the correct section.

On the other hand, if you’re just getting started with NumPy, I strongly suggest that you read the whole tutorial. Everything will make more sense that way.

Before we get into the specifics of the numpy.exp function, let’s quickly review NumPy.

If you’re just getting started with data science in Python, you’ve probably heard about NumPy, but you might not know exactly what it is. The NumPy module is very important for data science in Python, so you should understand what it is and what it does.

NumPy is essentially a Python module that deals with arrays of numeric data. You can think of these arrays like row-and-column structures, or like matrices from linear algebra.

They can be simple, like a 1-dimensional array:

Or they can be more complicated, like a 2-dimensional array:

NumPy even allows for multi-dimensional arrays.

Many NumPy functions simply enable you to create types of NumPy arrays, like the NumPy zeros functions, which creates NumPy arrays filled with zeroes and NumPy ones, which creates NumPy arrays filled with ones.

In addition to providing functions to *create* NumPy arrays, NumPy also provides tools for manipulating and working with NumPy arrays.

For example, there are tools for calculating summary statistics. NumPy has functions for calculating means of a NumPy array, calculating maxima and minima, etcetera.

NumPy also has tools for reshaping NumPy arrays. So you can use NumPy to change the shape of a NumPy array, or to concatenate two NumPy arrays together.

NumPy also has tools for performing common mathematical computations.

This is where the numpy.exp function comes in.

The NumPy exponential function (AKA, numpy.exp) is a function for calculating the following:

… where is the mathematical constant that’s approximately equal to 2.71828 (AKA, Euler’s number).

That’s it! That’s all it does!

Like all of the NumPy functions, it is designed to perform this calculation with NumPy arrays and array-like structures. So essentially, the np.exp function is useful when you need to compute for a large matrix of numbers.

So now that you know what the function does, let’s take a look at the actual syntax.

The syntax of np.exp (AKA, the NumPy exponential function) is extremely simple.

Before I show it to you though, I want to make an important point.

A very common convention in NumPy syntax is to give the NumPy module the alias “`np`

“.

Technically speaking, we give NumPy this nickname when we import the NumPy module. You can do it with the code `import numpy as np`

.

I just want to point this out, because in this tutorial (and specifically in this section about the syntax) I’m referring to NumPy as `np`

. That will only work properly though if you import NumPy with the code `import numpy as np`

.

I’ll show you this specifically when we look at some examples.

Ok. Let’s look at the syntax.

As I mentioned earlier, the syntax of the NumPy exponential function is extremely simple. It’s possibly one of the simplest NumPy functions.

Essentially, you call the function with the code `np.exp()`

and then inside of the parenthesis is a parameter that enables you to provide the inputs to the function.

It’s really, really simple.

Having said that though, let’s quickly talk about the parameters of np.exp.

There’s really only 1 parameter that we’re going to talk about, and that’s the `x`

parameter.

There are a few other parameters like `out`

and `where`

, but they are less commonly used, so we won’t cover them here.

Let’s quickly review the `x`

parameter.

`x`

(required)The `x =`

parameter enables you to provide the inputs to the `np.exp()`

function.

Technically, this input will accept NumPy arrays, but also single numbers (integers or floats) or array-like objects. So you can actually use Python lists and other array-like objects as inputs to the `x`

parameter.

Note that an input to this parameter is *required*. You must provide an input here.

Also, you don’t explicitly need to type `x =`

. You can actually leave it out and just type the name of the input array inside of the parenthesis.

Ok. Now that I’ve explained the syntax, let’s take a look at some examples.

Here, I’ll show you a few examples of how to use numpy.exp.

**Examples:**

- Use np.exp with a single number
- Use np.exp with a 1-dimensional array
- Using np.exp with multi-dimensional arrays

Before you run the following examples, make sure to import NumPy properly:

import numpy as np

As I explained earlier in this tutorial, this code will import NumPy with the nickname `np`

.

It will essentially enable you to refer to NumPy in your code as `np`

. This is a good shorthand that makes your code a little simpler and faster to write.

Moreover, this is just the common convention, so I want you to understand it.

The first example will be extremely simple.

Here, instead of using the numpy.exp function on an *array*, we’ll just use it with a single number as an input.

np.exp(2)

OUT:

7.38905609893065

This is really, really simple. This just calculates the value .

Remember: the value of is roughly 2.71828, so when we calculate , we’re basically calculating = (2.71828 * 2.71828).

As calculated by NumPy, = 7.38905609893065.

Next, let’s work with a slightly more complicated example.

Here, we’re going to use a list of numbers as the input.

To be clear, this is essentially identical to using a 1-dimensional NumPy array as an input. However, I think that it’s easier to understand if we just use a Python list of numbers.

Ok, we’re basically going to use the Python list `[0,1,2,3,4]`

as the input to the `x`

argument.

NumPy is going to calculate *for each of these numbers*.

Here’s the code:

np.exp([0,1,2,3,4])

And here’s the output:

array([ 1., 2.71828183, 7.3890561 , 20.08553692, 54.59815003])

So what happened here?

The numpy.exp function will take each input value, `[0,1,2,3,4]`

, and apply it as the exponent to the base .

Here, we’ve only used 4 values laid out in a Python list. But this will work in a similar way with a much longer list. You could have a list of hundreds, even thousands of values! The numpy.exp function will work the same.

Quickly, I want to re-do the above example with a proper NumPy array.

np_array_1d = np.array([0,1,2,3,4])

And let’s print it out:

print(np_array_1d)

OUT:

[0 1 2 3 4]

As you can see, this NumPy array has the exact same values as the Python list in the previous section.

Now, let’s compute the exponent with numpy.exp:

np.exp(np_array_1d)

OUT:

array([ 1. , 2.71828183, 7.3890561 , 20.08553692, 54.59815003])

This output is essentially identical to the output created with the Python list `[0,1,2,3,4]`

.

I want to show you this to reinforce the fact that numpy.exp can operate on Python lists, NumPy arrays, and any other array-like structure.

Finally, let’s use the numpy.exp function with a 2-dimensional array.

Here, we’ll use a NumPy array. We’ll create a 2-d array using numpy.arange, which we will reshape into a 2-d form with the NumPy reshape method.

np_array_2d = np.arange(9).reshape([3,3])

Quickly, let’s print out the array, so you can see the contents:

print(np_array_2d)

OUT:

[[0 1 2] [3 4 5] [6 7 8]]

As you can see, this is a 2-dimensional NumPy array that contains the numbers from 0 to 8.

Now, let’s compute for each of these values using numpy.exp.

np.exp(np_array_2d)

OUT:

array([[1.00000000e+00, 2.71828183e+00, 7.38905610e+00], [2.00855369e+01, 5.45981500e+01, 1.48413159e+02], [4.03428793e+02, 1.09663316e+03, 2.98095799e+03]])

Once again: numpy.exp is just computing for every value in the input array.

When you give it a 2d array, the NumPy exponential function simply computes for every input value x in the input array, and returns the result in the form of a NumPy array.

Keep in mind that np.exp works the same way for higher dimensional arrays!

Let’s quickly cover some frequently asked questions about the NumPy exponential function.

**Frequently asked questions:**

- What does numpy.exp do?
- What’s the difference between math.exp and numpy.exp?
- WTF is Euler’s Number?

It calculates for an array of input values, where is Euler’s number: 2.71828 …

For more information, read our fantastic tutorial about NumPy exponential.

Essentially, the `math.exp()`

function only works on scalar values, whereas `np.exp()`

can operate on *arrays of values*.

So you can use math.exp on a single number:

#THIS WORKS! import math math.exp(2)

But you can not use math.exp on an array-like object:

#THIS THROWS AN ERROR import math math.exp([1,2,3,4])

And as you saw earlier in this tutorial, the np.exp function works with both scalars and arrays.

Essentially, np.exp is more flexible than math.exp.

*The short answer*: Euler’s number (AKA, ) is an interesting and important mathematical constant. It’s a number!

The value of is roughly 2.7182818284590452353602874713527.

*The long answer*: it’s complicated.

How exactly we arrive at this constant and what it’s good for is sort of a long answer, and beyond the scope of this blog post.

At a high level though, is a very important number in mathematics. It shows up all over the place in math, physics, engineering, economics, and just about any place that deals with exponential growth, compounded growth, and calculus.

For more info, check out this Youtube video.

In this tutorial, you learned about the NumPy exponential function.

If you want to learn about other NumPy functions, we have quite a few other tutorials:

- How to create a NumPy array with np.arange
- A quick introduction to NumPy arrays
- How to calculate the mean of a NumPy array
- How to calculate the maximum of a NumPy array
- NumPy axes explained
- A quick introduction to concatenating NumPy arrays

Those are just a few though. We also have a variety of tutorials about Matplotlib and Pandas.

That said, if you want access to all of our FREE tutorials, then sign up for our email list.

When you sign up, you’ll get free tutorials on:

- NumPy
- Pandas
- Base Python
- Scikit learn
- Machine learning
- Deep learning
- … and more.

We regularly publish FREE data science tutorials. We publish tutorials about NumPy, Pandas, matplotlib, and data science in Python.

Additionally, we publish tutorials about data science in R.

If you want FREE data science tutorials, then sign up now.

The post How to use numpy exponential appeared first on Sharp Sight.

]]>The post A quick introduction to the numpy power function appeared first on Sharp Sight.

]]>**Contents**:

- An review of NumPy
- Introduction to numpy.power
- The syntax of numpy.power
- Examples of NumPy power
- Frequently asked questions about NumPy power

You can click on any of the above links and it will take you to the appropriate part of the tutorial.

So if you’re just looking for a quick answer to a question about the np.power function, just click on a link!

Having said that, if you’re new to NumPy, I recommend that you read the whole tutorial. NumPy can be a little complicated for beginners, and this tutorial is designed to give you a good overview of everything you need to know to use the np power function.

Very quickly, let’s review NumPy.

If you’re new to data science in Python, you might be a little confused about what exactly NumPy is.

It’s pretty simple. NumPy is a toolkit for working with arrays of numbers in Python.

Python (as I hope you know) is a very common programming language. And increasingly, Python has become one of the most important programming languages for doing data science.

One of the reasons for the popularity of Python in the data science community is that it has a set of modules that are excellent for doing data science tasks:

- Pandas enables you to manipulate dataframes
- Matplotlib gives you tools for data manipulation
- NumPy enables you to work with numeric data

Essentially, Python gives you a set of tools for doing almost every part of the data science workflow.

As I’ve mentioned, NumPy focuses on working with numbers.

Specifically, NumPy has tools that enable you to:

- calculate the median of a NumPy array
- calculate the mean of a NumPy array
- sum the values of a NumPy array
- concatenate two separate NumPy arrays
- generate a random sample from a NumPy array

… and more.

There are several dozen functions in the NumPy package … it’s a little hard to list them all.

Essentially, NumPy provides a toolkit for analyzing, reshaping, and working with NumPy arrays, which are arrays of numeric data in Python.

As such, NumPy has tools that enable you to perform a variety of mathematical computations on numbers and arrays of numbers.

One of those tools is the NumPy power function.

So what is the NumPy power function?

It’s pretty simple.

In its simplest form, numpy.power is just a tool for performing exponentiation in Python.

You almost certainly learned about exponentiation early in your school career. When we perform exponentiation, we raise one number b, called the base, to another number n, called the exponent. The exponent n is also sometimes called the “power.”

As explained by Wikipedia, this operation amounts to multiplying the base b by itself n times:

\[\large b^n = \underbrace{b \times \cdots \times b}_{n \text{ times}}\]

When we do this, we say that we raise b to the power of n.

The np.power function enables you to do this.

But in addition to allowing you to do this with single numbers, you can also do this with *arrays of numbers*.

How this works in practice can be a little complicated, but in essence, NumPy power just a tool for performing mathematical exponentiation with arrays of numbers.

So while the numpy.power function enables you to perform simple exponentiation like b to the power of n, it also allows you to do this with large NumPy arrays.

I want to show you some examples of how this works (to develop your intuition), but before I do that, I want to explain the syntax.

Once you understand the syntax, the examples themselves will be much easier to understand.

Here, let’s just take a look at the syntax at a high level.

The syntax is really very simple, but to really “get it” you should understand exactly what the parameters are.

In the image of the syntax above, there are two parameters:

`array-of-bases`

`array-of-exponents`

In the official documentation for the np.power function, these are called `x1`

and `x2`

.

But as is often the case with the official NumPy documentation, I think those names are unintuitive. That being the case, I’m referring to `x1`

and `x2`

as `array-of-bases`

and `array-of-exponents`

respectively.

`array-of-bases`

(required)The first parameter of the np.power function is `array-of-bases`

.

As this implies, the argument to this parameter should be an array of numbers. These numbers will be used as the “bases” of our exponents.

Note that this is required. You must provide an input here.

Also, the item that you supply can take a variety of forms. You can supply a NumPy array, but you can also supply an array-like input. The array-like inputs that will work here are things like a Python list, a Python tuple or one of the other Python objects that have array-like properties.

Keep in mind that you can also just supply a single integer!

`array-of-exponents`

(required)The second parameter is `array-of-exponents`

, which enables you to specify the exponents that you will apply to the bases, `array-of-bases`

.

Note that just like the `array-of-exponents`

input, this input must be a NumPy array or an array-like object. So here you can supply a NumPy array, a Python list, a tuple, or another Python object with array-like properties. You can even provide a single integer!

Note that both arguments, `array-of-bases`

and `array-of-exponents`

, are *positional* arguments.

Positional arguments are a little confusing to beginners, but here’s a quick explanation.

How each input to np.power is used depends on where you put it inside of `np.power()`

.

Inside of `np.power()`

, you must put the bases first and you must put the exponents second. The *position* of the argument inside of `np.power()`

determines how it is used by the function.

Note that this is in contrast to so-called “keyword arguments.” With keyword arguments, you use a particular keyword to designate an input to a function. And as long as you use the correct keywords, they can be in any order you’d like.

So essentially, if the argument is a “positional argument,” the order maters.

And because `array-of-bases`

and `array-of-exponents`

are positional arguments, the bases must be specified first and the exponents must be specified second inside of the function.

Again, this is a little confusing, so be on the lookout for a future tutorial about positional arguments.

Ok. Now that you’ve learned a little about the syntax, let’s look at some real examples of how to use numpy.power.

We’re going to work with a few examples, starting with the simplest and then progressing through examples that are more complicated.

**Examples**:

- Raise an integer to a power
- Calculate the exponent of an array
- Use two 1-d arrays in numpy.power
- An example of “broadcasting”

Before you fun the code in the following examples, you’ll need to run a small piece of code first.

You essentially need to import NumPy and give it an “alias.”

import numpy as np

When we do this, we essentially designate the code `np`

as the “nickname” or alias of the `numpy`

module.

This is a very common convention in Python, and it allows you to call a function starting with `np`

. You’ll see what I mean in a minute.

First, we’re going to work with a *very* simple example.

Here, we’re just going to raise an integer to a power.

To do this, we’ll call the NumPy power function with the code `np.power()`

. Then inside of the parenthesis, we’ll provide two arguments …. the base and the exponent.

np.power(2,3)

OUT:

8

This is very simple. It just calculates 2 to the 3rd power which equals 8.

Notice how the inputs work. The first input (2) is the base and the second input (3) is the exponent.

This is exactly how the remaining examples will work.

Let’s take a look at a more complicated example.

Here, we’re going to change things up a little bit.

Instead of the base being a single integer, the base will be a group of numbers organized into an array-like object (i.e., a Python list).

To be clear, we typically use np.power on *NumPy arrays*. However, I think that everything is easier to understand if we just use a Python list instead. By using a Python list, you’ll actually be able to see all of the numbers inside of the syntax.

In this example, the bases will be a simple list of numbers from 0 to 4: `[0,1,2,3,4]`

.

This list will be the first input to the np.power function. We’re going to raise each element of this list to the 2nd power.

np.power([0,1,2,3,4], 2)

Which produces the following output:

array([ 0, 1, 4, 9, 16])

This is pretty straight forward once you understand what’s going on here.

Essentially, the np.power function takes the elements of the list and uses those as the *bases*. Then, it applies the exponent (the second argument to the function) to every base.

So np.power simply applies the exponent 2 to every single base in the first input array.

And the output of the function is a new NumPy with the computed exponential values.

Now, let’s just re-do this example with a NumPy array instead of a Python list.

As I mentioned above … everything is easier to understand and see when we use a Python list, but we’ll often need to use the np.power function on actual NumPy arrays.

So, I’ll just show you the same example with a NumPy array in place of the Python list.

First, we’ll just create a NumPy array using np.arange:

array_1d = np.arange(5)

This array just contains the numbers from 0 to 4.

Then, we’ll use np.power to calculate the exponent:

np.power(array_1d, 2)

Which produces the following output:

array([ 0, 1, 4, 9, 16])

In terms of outputs, this example creates the same output as `np.power([0,1,2,3,4], 2)`

. So just remember that NumPy power will work with NumPy arrays, Python lists, or any array-like object.

Ok. Now that we’ve taken a look at some simple examples, let’s move on to something more complicated.

Here, we’re going to use *two* input arrays instead of one array and one number.

But keep in mind, we’re actually going to use Python lists instead of proper NumPy arrays, just for the sake of clarity.

The first list is going to be the list of bases, and the second list will be the list of exponents.

np.power([2,2,2,2,2], [0,1,2,3,4])

Which produces the following output:

array([ 1, 2, 4, 8, 16])

So what happened here?

The first input list – `[2,2,2,2,2]`

– is the list of *bases*.

The second input list – `[0,1,2,3,4]`

– is the list of *exponents*.

Recall the previous examples.

In an example like `np.power(2,3)`

, the first argument is the base and the second argument is the exponent.

The code `np.power([2,2,2,2,2], [0,1,2,3,4])`

is essentially the same! The first list is the bases, and the second list is the exponents.

The only major difference is how these inputs are put together to produce the output.

NumPy applies the exponents to the bases *element wise*. This means that it applies the first exponent to the first base, the second exponent to the second base, and so on.

Considering that our input lists are fairly simple, this is still a fairly simple example. But it shows you how powerful (heh heh) the np.power function is when you start working with arrays and array like objects.

Ok. Now let’s move on to a more complicated example where we have a multi dimensional array of bases.

Here, we’re going to use the NumPy power function to compute exponents for a 2-dimensional array of bases.

Moreover, the *exponents* will also be in an array-like structure.

Let’s take a look at the example and then I’ll explain exactly how NumPy handles this.

First, let’s create the input array. This is actually going to be a NumPy array, instead of a Python list.

To create this array, we’ll simply use the np.array function.

array_2d = np.array([[0,0,0,0,0],[1,1,1,1,1],[2,2,2,2,2],[3,3,3,3,3]])

Let’s can print it out, so you can see it:

print(array_2d)

OUT:

[[0 0 0 0 0] [1 1 1 1 1] [2 2 2 2 2] [3 3 3 3 3]]

This is a fairly simple 2-dimensional NumPy array. As you can see, the first row has all 0s, the second row has all 1s, and so on.

Now, let’s run the np.power function on this and apply some exponents to these bases.

np.power(array_2d, [0,1,2,3,4])

Which produces the following output:

array([[ 1, 0, 0, 0, 0], [ 1, 1, 1, 1, 1], [ 1, 2, 4, 8, 16], [ 1, 3, 9, 27, 81]])

What happened here?

You have to think about the structure of the inputs.

The first argument – the array of bases – is a 2-dimensional array. The second argument – the exponents – is a 1-dimensional array. And notice that they both have the same number of columns.

In a case like this, the NumPy power function is sort of smart. It applies the exponents to *every row*.

It still does this element-wise, meaning that the exponent of column 0 is applied to the base of column 0 …. the exponent of column 1 is applied to the base of column 1, and so on.

But essentially, it applies the exponents to every row.

This behavior is called *broadcasting*, and it appears quite a bit in NumPy when you’re working with arrays that have different dimensions. A full explanation of broadcasting is beyond the scope of this post. Just understand that this is common in NumPy, and you’ll probably need to understand how it works.

Before I end the tutorial, let’s quickly discuss any frequently asked questions.

**Frequently asked questions**:

No, NumPy power doesn’t work with negative exponents.

So for example, if you try, you’ll get an error:

np.power(2, -1)

ValueError: Integers to negative integer powers are not allowed.

If you want to use negative exponents, use `numpy.float_power()`

instead.

Do you have any other questions about the NumPy power function?

Leave your question in the comments below.

NumPy is extremely powerful, and very important for data science in Python.

That being the case, if you’re interested in data science in Python, you should really learn more about Python.

You can learn more by checking out our other tutorials:

- How to use the NumPy max function
- Numpy axes explained
- A quick introduction to the NumPy array
- How to use Numpy reshape
- How to use the NumPy zeros function

… and more.

I also suggest that you check out our tutorials about matplotlib and Pandas. For example, we have tutorials about the Pandas dataframe, the Pandas iloc method, and more.

Ultimately, if you’re interested in data science in Python, there’s a lot to learn.

The good news is that we provide FREE data science tutorials here at Sharp Sight.

If you sign up for our email list, you’ll get our tutorials delivered FOR FREE right to your inbox.

When you sign up, you’ll get free tutorials on:

- NumPy
- Pandas
- Base Python
- Scikit learn
- Machine learning
- Deep learning
- … and more.

Want to learn data science?

Sign up right now …

The post A quick introduction to the numpy power function appeared first on Sharp Sight.

]]>