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):
JavaScript
x
8
1
import pandas as pd
2
import numpy as np
3
data = {'range_0.5' : [0,0.5,1,1.5,2, np.nan, np.nan, np.nan, np.nan],
4
'range_0.25' : [0,0.25,0.5,0.75,1,1.25,1.5,1.75,2]}
5
6
df = pd.DataFrame(data)
7
df
8
Here is what I have tried:
JavaScript
1
7
1
import numpy
2
x = []
3
seq = [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625]
4
5
for i in seq:
6
x = range(0, 2, i)
7
The following error is thrown:
JavaScript
1
7
1
TypeError Traceback (most recent call last)
2
Input In [10], in <cell line: 1>()
3
1 for i in seq:
4
----> 2 x = range(0, 2, i)
5
6
TypeError: 'float' object cannot be interpreted as an integer
7
How can I properly create my loop?
Advertisement
Answer
np.arange()
You can use numpy.arange()
which supports floats as step values.
JavaScript
1
5
1
import numpy as np
2
3
for step in [0.5, 0.25]:
4
print([i for i in np.arange(0, 2, step))
5
Expected output:
JavaScript
1
3
1
[0.0, 0.5, 1.0, 1.5]
2
[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75]
3
To include 2
just add the step value once again:
JavaScript
1
3
1
for step in [0.5, 0.25]:
2
print([i for i in np.arange(0, 2 + step, step)])
3
Expected output:
JavaScript
1
3
1
[0.0, 0.5, 1.0, 1.5, 2.0]
2
[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0]
3
np.linspace()
Alternatively you can use np.linspace()
:
This has the ability to include the endpoint using endpoint=True
;
JavaScript
1
3
1
for step in [0.5, 0.25]:
2
print([i for i in np.linspace(0, 2, int(2 // step) + 1, endpoint=True)])
3
Expected output:
JavaScript
1
3
1
[0.0, 0.5, 1.0, 1.5, 2.0]
2
[0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0]
3