-1

I am using python and asking for help on how to simplify the code below. Thanks.

for i in range(1,9):
    if i == 1:
        wt_1 = gwt_2018[gwt_2018.WkNum == i]
    elif i == 2:
        wt_2 = gwt_2018[gwt_2018.WkNum == i]
    elif i == 3:
        wt_3 = gwt_2018[gwt_2018.WkNum == i]
    elif i == 4:
        wt_4 = gwt_2018[gwt_2018.WkNum == i]
    elif i == 5:
        wt_5 = gwt_2018[gwt_2018.WkNum == i]
    elif i == 6:
        wt_6 = gwt_2018[gwt_2018.WkNum == i]
    elif i == 7:
        wt_7 = gwt_2018[gwt_2018.WkNum == i]
    else i == 8:
        wt_8 = gwt_2018[gwt_2018.WkNum == i]
2
  • 1
    Let's start with synthax: gwt_2018.WkNum == i will be evaluated to either True or False. Is that your intent? Does gwt_2018 have a True or False key? Commented Aug 24, 2018 at 8:28
  • Are we supposed to guess what gwt_2018 is and what this code is supposed to do ? Commented Aug 24, 2018 at 8:57

3 Answers 3

0

Do you need something like this?

l = [wt_1, wt_2, wt_3, wt_4, wt_5, wt_6, wt_7, wt_8]
for index, i in enumerate(l):
    i = gwt_2018[gwt_2018.WkNum == index+1]
Sign up to request clarification or add additional context in comments.

Comments

0

Is that mandatory to have 'wt_i' as variable name for all i's ?

I would use a dictionary instead:

wt = {}
for i in range(1,9):
    wt[i] = gwt_2018[gwt_2018.WkNum == i]

1 Comment

Thank you for the quick reply. I did find the solution for my problem. gbl = globals() for i in range(1,54): gbl['df_'+str(i)] = gwt_2018[gwt_2018.WkNum == i]
0

I found the solution [a link] (Create multiple dataframe using for loop in python 2.7)

gbl = globals()
for i in range(1,54):
    gbl['df_'+str(i)] = gwt_2018[gwt_2018.WkNum == i]

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.