All hail the power of broadcasting!
import pandas as pd
import random
import numpy as np
# example data
lows = pd.Series(np.random.uniform(0, 50, 10))
highs = pd.Series(np.random.uniform(0, 50, 10))
nums_arr = random.uniform(low=lows, high=highs)
I especially like this solution because it directly creates a Series, no conversions necessary.
A few comments on your code:
1)
Variable names should generally follow the lower_case_with_underscores
style. See PEP 8 for more on Python style.
2)
Low = pd.Series(data['LOW']).values
High = pd.Series(data['HIGH']).values
From the rest of the code you showed me, you already know that data
is a DataFrame. Getting a column from a DataFrame (e.x: data['LOW']
) returns a Series, so the call to pd.Series()
is redundant. It also isn't clear why you then call .values()
.
Bear in mind that using Series.values
is discouraged. From the docs:
Warning: We recommend using Series.array or Series.to_numpy(), depending on whether you need a reference to the underlying data or a NumPy array.
3)
newlist = []
for i in range(0, 8):
newlist = random.uniform(Low, High)
I'm really struggling to find the words to explain this one. random.uniform
is a function which takes two numbers, and produces a random float between the first two. In this case, however, random.uniform
is operating on two Series, thanks to the magic of broadcasting. This is why despite not looking like it makes much sense, the code doesn't actually produce an error or crash.
Notice also that the code above doesn't actually do anything with the result in newlist
, nor does newList
depend at all on the variable i
.
My guess is that you had something like this in mind:
# notice the variable name
new_nums_list = []
for i in range(low.size):
curr_rand_num = random.uniform(low[i], high[i])
new_nums_list.append(curr_rand_num)
Which could have also been written:
new_nums_list = [random.uniform(low[i], high[i]) for i in range(low.size)]
Thanks to the power of zip()
, we could do even better:
new_nums_list = [random.uniform(curr_low, curr_high) for curr_low, curr_high in zip(low, high)]
Any further questions? :)