Printing between two number ranges with a given step value

Question:

I am new to loops, and I am trying to iterate over all items in a list, and I need to generate the values between 0 and 2 with a given step value. I have tried to use the "range" function, but cannot get it to work.

The end result should look something like this (doesn’t have to be in a pandas dataframe, just for illustrative purposes):

import pandas as pd
import numpy as np
data = {'range_0.5' : [0,0.5,1,1.5,2, np.nan, np.nan, np.nan, np.nan],
      'range_0.25' : [0,0.25,0.5,0.75,1,1.25,1.5,1.75,2]}

df = pd.DataFrame(data)
df

Here is what I have tried:

import numpy
x = []
seq = [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625]

for i in seq:
    x = range(0, 2, i)

The following error is thrown:

TypeError                                 Traceback (most recent call last)
Input In [10], in <cell line: 1>()
      1 for i in seq:
----> 2     x = range(0, 2, i)

TypeError: 'float' object cannot be interpreted as an integer

How can I properly create my loop?

Asked By: s_o_c_account

||

Answers:

np.arange()

You can use numpy.arange() which supports floats as step values.

import numpy as np

for step in [0.5, 0.25]:
    print([i for i in np.arange(0, 2, step))

Expected output:

[0.0, 0.5, 1.0, 1.5]
[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75]

To include 2 just add the step value once again:

for step in [0.5, 0.25]:
    print([i for i in np.arange(0, 2 + step, step)])

Expected output:

[0.0, 0.5, 1.0, 1.5, 2.0]
[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0]

np.linspace()

Alternatively you can use np.linspace():
This has the ability to include the endpoint using endpoint=True;

for step in [0.5, 0.25]:
    print([i for i in np.linspace(0, 2, int(2 // step) + 1, endpoint=True)])

Expected output:

[0.0, 0.5, 1.0, 1.5, 2.0]
[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0]
Answered By: Mushroomator
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.