Np arange python что это
Перейти к содержимому

Np arange python что это

  • автор:

numpy.arange#

arange can be called with a varying number of positional arguments:

arange(stop) : Values are generated within the half-open interval [0, stop) (in other words, the interval including start but excluding stop).

arange(start, stop) : Values are generated within the half-open interval [start, stop) .

arange(start, stop, step) Values are generated within the half-open interval [start, stop) , with spacing between values given by step .

For integer arguments the function is roughly equivalent to the Python built-in range , but returns an ndarray rather than a range instance.

When using a non-integer step, such as 0.1, it is often better to use numpy.linspace .

See the Warning sections below for more information.

Parameters : start integer or real, optional

Start of interval. The interval includes this value. The default start value is 0.

stop integer or real

End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

step integer or real, optional

Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] — out[i] . The default step size is 1. If step is specified as a position argument, start must also be given.

dtype dtype, optional

The type of the output array. If dtype is not given, infer the data type from the other input arguments.

like array_like, optional

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

New in version 1.20.0.

Array of evenly spaced values.

For floating point arguments, the length of the result is ceil((stop — start)/step) . Because of floating point overflow, this rule may result in the last element of out being greater than stop.

np.arange() — How To Use the NumPy arange() Method

NumPy is a Python library widely considered to be the most important library for numerical computing.

Within NumPy, the most important data structure is an array type called np.array().

NumPy contains a number of methods that are useful for creating boilerplate arrays that are useful in particular circumstances. One of these methods is np.arange() .

In this article, I will teach you everything you need to know about the np.arange() method. By the end of this article, you will know np.arange()’s characteristics, uses, and properties, and will feel comfortable integrating this method into your Python applications.

Table of Contents

You can use the links below to navigate to a particular section of this tutorial:

How To Import NumPy

To use the np.arange() method, you will first need to import the NumPy library into your Python script. You can do this with the following code:

Now that this import has been completed, we are ready to start learning about the np.arange() method!

How to Use The Np.arange() Method

To start, let’s discuss how to use NumPy’s np.arange() method.

The np.arange() method creates a very basic array based on a numerical range that is passed in by the user.

More specifically, a basic form of the np.arange() method takes in the following arguments:

  • start : the lowest value in the outputted NumPy array
  • stop the highest value (exclusive) from the outputted NumPy array

The output of the np.arange() method is a Numpy array that returns every integer that is greater than or equal to the start number and less than the stop number.

To be specific, the np.arange() method includes the lower endpoint but excludes the lower endpoint.

Let’s consider a few examples:

It is possible to run the np.arange() method while passing in a single argument. In this case, the np.arange() method will set start equal to 0 , and stop equal to the number that you pass in as the sole parameter.

Single-argument np.arange() methods are useful for creating arrays with a desired length, which is helpful in writing loops (we’ll explore this more later).

A few examples of single-argument np.arange() methods are below:

The np.arange() method also accepts optional third and fourth arguments: step and dtype . We will explore both of these parameters next.

The np.arange() Method’s step Argument

NumPy’s np.arange() method accepts an optional third argument called step that allows you to specify how much space should be between each element of the array that it returns. The default value for step is 1 .

As an example, let’s consider the np.arange() method that generates a NumPy array of all the integers from 0 to 9 (inclusive):

If we wanted to generate the same list but only include elements that had a space of 5 integers between them, we could specify step=5 :

In fact, you do not need to actually specify the step= component of the argument. The following code generates the same output:

Data Types and the Np.arange() Method

NumPy’s np.arange() method accepts an optional fourth argument called dtype that allows you to specify the type of data contained in the NumPy array that it generates. Since dtype is optional, it is fine to omit it from the np.arange() method.

The default value for dtype is None . This means that when you do not specify a value for dtype , then the np.arange() method will attempt to deduce what data type should be used based on the other three arguments.

Before diving into how the np.arange() method determines data types when they are not specified, there is one very important concept you should understand about how NumPy arrays work.

All of the elements in a NumPy array must be of the same data type. So an array cannot contain both floating-point numbers and integers. It must have all floating-point numbers or all integers.

This common data type is also referred to as dtype and can be accessed as an attribute of the array object using the dot operator.

As an example, if we run the following code:

Then Python will print int64 , which is the value of dtype for the NumPy array.

NumPy has several different values for dtype that are available ot users. Here are a few examples for integers specifically:

  • np.int8: a signed integer with 8 bits
  • np.uint8: an unsigned integer with 8 bits
  • np.int16: a signed integer with 16 bits
  • np.uint16: an unsigned integer with 16 bits

If you’re interested in learning more about the data types available within NumPy, please read their documentation page to learn more.

How To Count Backwards With NumPy’s np.arange() Method

It is possible to use NumPy’s np.arange() method to create a NumPy array that lists its elements in descending order (instead of ascending order, which is the default). This section will show you how.

We have created NumPy arrays whose elements are in ascending order by listing a smaller number following by a larger number, like this:

To create a NumPy array whose elements are listed in descending order, all we need to do is list the elements backwards and specify a negative value for the step argument! Here is an example:

We can also use this strategy while specifying a value for the dtype argument. Here is an example:

How To Generate Empty NumPy Arrays With np.arange()

There are certain cases where you will want to generate empty NumPy arrays. It is possible to do this using NumPy’s np.arange() method.

First let’s talk about why you might want an empty NumPy array. As an example, consider the situation where you are storing transaction history in a NumPy array before inserting it into a database. In this case, you’d want to begin with an empty array and add to it over time.

The NumPy np.arange() method allows you to easily generate empty NumPy arrays. To do this, all that is required is for you to list the same number twice.

A few examples are below:

The reason this returns an empty array is because the np.arange() method is designed to exclude the upper endpoint (which, in this case, is actually equal to the lower endpoint).

How To Create Tuples Using NumPy’s np.arange()

While NumPy’s np.arange() method is primarily used to create NumPy arrays, it is also possible to use np.arange() to create other data structures. I’ll show you how to create tuples using np.arange() in this section.

First, let’s create a basic NumPy array using the np.arange() method:

If we wrap this NumPy array in Python’s built-in tuples function, we can easily turn this array into a tuple!

You can wrap this new data structure in a type function to make sure that it is indeed a tuple:

How To Create Sets Using NumPy’s np.arange()

In the last section, I showed you how to create Python tuples using NumPy’s np.arange() method. We will see in this section that the strategy for creating Python sets using NumPy’s np.arange() method is quite similar.

First, create a NumPy array using np.arange():

Then, just like we did when learning about tuples, we’ll wrap the entire NumPy array in a set() function:

As before, we can wrap this new data structure in a type function to make sure that it is indeed a set:

How To Use Numpy’s np.arange() Method To Write Loops

One of the more common use cases for NumPy’s np.arange() method is to create arrays of integers to loop over in a for loop. In this section, I will demonstrate how to use np.arange() to write loops using two examples.

In a for loop, you can use the np.arange() method by placing it after the in keyword, like this:

In the code above, we loop over the array object array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) and multiply each element against the number variable.

Let’s consider another example:

The Differences Between Python’s Built-In Range Function and NumPy’s np.arange() Method

So far in this article, I have performed a deep dive into the capabilities of NumPy’s np.arange() method.

Anyone who has done much Python programming before may notice that np.arange() is quite similar to Python’s built-in range() function.

Because of this, I will conclude this article by providing a comparison of the range() function and the np.arange() method.

The first — and most obvious — difference between range() and np.arange() is that the former is a built-in Python function, while the latter comes with NumPy. Because of this, you can’t use np.arange() unless you’ve already imported the NumPy numerical computing library.

Second, let’s compare what their outputs look like. When you run the built-in range method, you get a special range class:

This is different from np.arange(), which returns a NumPy array (as we’ve seen many times in this tutorial).

Lastly, let’s compare their parameters. Both functions accept the start , stop , and step arguments, which is one important commonality. However, range() has an important limitation — it can only work with integers! If you pass in any other data type, you will get a TypeError .

Arange (NumPy) in Python

Little Dino

The arange function basically creates a sequence of numbers with incremental step. It’s a function in NumPy package, so you have to first import Numpy (see how to import) before using this function.

If you know how to use range function, then you probably already understand how to use arange since they do the exact same thing (check out the range introduction)!

The basic structure of arange function is np.range(start, stop, step) . There are 3 arguments, but ONLY stop is mandatory. In other words, you can leave start and step as default. By default, start is 0, step is 1.

Let’s look at a few examples.

  • np.arange(5)

It returns array([0, 1, 2, 3, 4]). Because we only pass 1 parameter, Python recognizes it as stop , and interpret the expression as np.arange(0,5,1) .

⚡ The stop itself is EXCLUDED! Since Python is 0-indexed, the fifth position is actually 4 (e.g., array([0, 1, 2, 3, 4])).

  • np.arange(2,5)

It returns array([2, 3, 4]). Because we now pass 2 parameters, Python recognizes them as start and stop , and interpret the expression as np.arange(2,5,1) .

⚡ Remember the basic structure of arange function is (start, stop, step) . If we don’t specify the argument names, Python automatically views the first argument as start , the second as stop , and the third as step .

  • np.arange(2,5,2)

Now the step is introduced. It returns array([2, 4]). We assign step as 2, which means only every second element will be selected. Therefore, the element 3 is excluded.

  • np.arange(5,0,-1)

Well, this one looks strange. It returns array([5, 4, 3, 2, 1]). Since the step is -1, we actually extract elements in a reverse order. Namely, we start from 5, and we move in decremental steps.

⚡ If the step is negative (decremental), start MUST be larger than stop . It’s quite obvious because you can’t move from a small number to a large one in decremental steps!

⚡ The sequence returned is a NumPy array, not a list, so you can apply any Numpy function to this object!

NumPy: numpy.arange() function

The numpy.arange() function is used to generate an array with evenly spaced values within a specified interval. The function returns a one-dimensional array of type numpy.ndarray.

Syntax:

NumPy array: arange() function

Parameters:

Name Description Required /
Optional
start Start of interval. The interval includes this value. The default start value is 0. Optional
stop End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. Required
step Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] — out[i]. The default step size is 1. If step is specified as a position argument, start must also be given. Optional
dtytpe The type of the output array. If dtype is not given, infer the data type from the other input arguments. Optional

Return value:

arange : ndarray — Array of evenly spaced values.
For floating point arguments, the length of the result is ceil((stop — start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.

Example: arange() function in NumPy.

In the above example the first line of the code creates an array of integers from 0 to 4 using np.arange(5). The arange() function takes only one argument, which is the stop value, and defaults to start value 0 and step size of 1.
The second line of the code creates an array of floating-point numbers from 0.0 to 4.0 using np.arange(5.0). Here, 5.0 is provided as the stop value, indicating that the range should go up to (but not include) 5.0. Since floating-point numbers are used, the resulting array contains floating-point values.
Both arrays have the same length and contain evenly spaced values.

Pictorial Presentation:

NumPy array: arange() function
NumPy array: arange() function

Example: Numpy arange function with start, stop, and step arguments

In the above code ‘np.arange(5,9)’ creates an array of integers from 5 to 8 (inclusive).
In the second example, ‘np.arange(5,9,3)’ creates an array of integers from 5 to 8 (inclusive) with a step size of 3. Since there is no integer between 5 and 8 that is evenly divisible by 3, the resulting array only contains two values, 5 and 8.

Python — NumPy Code Editor:

Previous: loadtxt()
Next: linspace()

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *