0

This is an if statment inside a loop that seems inefficient the first loop changes parts of the code to 2nd 3rd and 4th. as you can see I had to manually write q2 names q3 names q4 names for example is there a way that will change without have to write it out like this? thank you

    if qtr == "2ND":
        Q2_names_e = re.findall(r'^(\d{2,4})\s+\w+\s+\w+', text, re.MULTILINE)
        Q2_names.append(Q2_names_e)
        lines = text.split('\n')
        df1 = pd.DataFrame([line.split() for line in lines])
        for index, row in df1.iterrows():
            if row[1] == 'EARNINGS:':
                Q2_Pay_e =row[3]
                Q2_Pay.append(Q2_Pay_e)
    elif qtr == "3RD":
        Q3_names_e = re.findall(r'^(\d{2,4})\s+\w+\s+\w+', text, re.MULTILINE)
        Q3_names.append(Q3_names_e)
        lines = text.split('\n')
        df2 = pd.DataFrame([line.split() for line in lines])
        for index, row in df2.iterrows():
            if row[1] == 'EARNINGS:':
                Q3_Pay_e =row[3]
                Q3_Pay.append(Q3_Pay_e)
    elif qtr == "4TH":
        Q4_names_e = re.findall(r'^(\d{2,4})\s+\w+\s+\w+', text, re.MULTILINE)
        Q4_names.append(Q4_names_e)
        lines = text.split('\n')
        df3 = pd.DataFrame([line.split() for line in lines])
        for index, row in df3.iterrows():
            if row[1] == 'EARNINGS:':
                Q4_Pay_e =row[3]
                Q4_Pay.append(Q4_Pay_e)
    else:
        break      

i treid adding {} but will not allow me to do that like in the example i gave Q{qtr} Names within the original loop

Barmar
  • 741,623
  • 53
  • 500
  • 612
Dmata
  • 1
  • 1
  • Don't use separate variables, use a dictionary whose keys are the quarter names. – Barmar Jan 06 '23 at 18:03
  • All of the conditions are doing the same thing? Do you even need those conditions? The only different lines seem to be `Q2_Pay.append(Q2_Pay_e)`, etc., why don't you simply move your condition there? Also as Barmar suggests maybe `Q2_Pay`, `Q3_Pay`, etc. can even be stored in a dictionary making that even simpler. – Abdul Aziz Barkat Jan 06 '23 at 18:03
  • the values of these are stored in a list [ ] for exampl Q2_Pay[ ] will dictionary allow me to store the value that are obtained into a list? I use the list to create a data frame then that data frame goes into an excel sheet. – Dmata Jan 06 '23 at 18:26

0 Answers0