1

I am trying to create an if statement to check a condition for each iteration

          for in range(100):
            B10 = np.random.randint(0, precip.shape[0])
            T10 = np.random.randint(0, precip.shape[0] )

            if np.abs(B10-T10) <=30:
                T10 = np.random.randint(0, precip.shape[0])

I want to create an if condition that will get new values of T10 until the condition above is met for every iteration. How can I do this?

3
  • 2
    until the condition above is met - while loop? Commented Sep 25, 2019 at 14:57
  • Can you include example dataframe with expected output? Commented Sep 25, 2019 at 14:57
  • @h4z3 something of sort, just not sure how to use it in my code Commented Sep 25, 2019 at 14:59

4 Answers 4

3

Use a while loop instead of a for loop:

B10 = np.random.randint(0, precip.shape[0])
T10 = np.random.randint(0, precip.shape[0])
while np.abs(B10-T10) <= 30:
    B10 = np.random.randint(0, precip.shape[0])
    T10 = np.random.randint(0, precip.shape[0])

or you can avoid redeclaring variables using the following:

while True:
    B10 = np.random.randint(0, precip.shape[0])
    T10 = np.random.randint(0, precip.shape[0])
    if not (np.abs(B10-T10) <=30):
        break

In general, it is a good practice to use a for loop when you know the number of iterations of your loop or when you are using collections. However, when you don't know it, i.e., when it depends on a condition, you should use a while loop.

Sign up to request clarification or add additional context in comments.

Comments

1

Avoid the loop and the if statement by generating the random numbers your want. In your code, T10 will be a random value between max(0, B10 - 30) and min(UB, B10 + 10), inclusive.

max_delta = 30
B10 = np.random.randint(0, UB)
T10 = np.random.randint(max(0, B10 - max_delta), min(UB, B10 + max_delta  + 1))

where UB = precip.shape[0].

Comments

1

If I get you right, this should do it:

df['B10'] = np.random.randint(0, df.shape[0], df.shape[0])
df['T10'] = df['B10'].apply(lambda x: np.random.randint(0, x+1))

Comments

1
T10 = np.random.randint(0, precip.shape[0])
while True:
    B10 = np.random.randint(0, precip.shape[0])
    T10 = np.random.randint(0, precip.shape[0])
    if not (np.abs(B10-T10) <=30):
        break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.