1

I tried to create the loop in python. The code can be seen below.

df=pd.DataFrame.copy(mef_list)
form=['','_M3','_M6','_M9','_M12','_LN','_C']
for i in range(0, len(form)):
    df=pd.DataFrame.copy(mef_list)
    df['Variable_new']=df['Variable']+str(form[i])

When I run the code, the result is only from the last loop, which is variable+'_C' I think it is because the data frame (df) is always replaced when the new loop start. In order to avoid the issue, I would think that if the data frame (df) could be renamed by plus the number of loop, the problem would be solved.

I used str function and hope to get df0, df1, ...,df6 but it doesn't work with the data frame name. Please suggest me how to change the name of data frame by add number of loop and also I still open for any alternative way.

Thanks!

2
  • 2
    Please don't post codes as images. Commented Aug 17, 2018 at 13:10
  • @Nouman Thanks, revised Commented Aug 17, 2018 at 13:28

2 Answers 2

5

This isn't a pythonic thing to do, have you thought about instead creating a list of dataframes?

df=pd.DataFrame.copy(mef_list)
form=['','_M3','_M6','_M9','_M12','_LN','_C']
list_of_df = list()
for i in range(0, len(form)):
    df=pd.DataFrame.copy(mef_list)
    df['Variable_new']=df['Variable']+str(form[i])
    list_of_df.append(df)

Then you can access 'df0' as list_of_df[0]

You also don't need to iterate through a range, you can just loop through the form list itself:

form=['','_M3','_M6','_M9','_M12','_LN','_C']
list_of_df = list()
for i in form:
    df=pd.DataFrame.copy(mef_list)
    df['Variable_new']=df['Variable']+str(i) ## You can remove str() if everything in form is already a string
    list_of_df.append(df)
Sign up to request clarification or add additional context in comments.

Comments

0
mef_list = ["UR", "CPI", "CEI", "Farm", "PCI", "durable", "C_CVM"]
form = ['', '_M3', '_M6', '_M9', '_M12', '_LN', '_C']
Variable_new = []
foo = 0
for variable in form:
     Variable_new.append(mef_list[foo]+variable)
     foo += 1
print(Variable_new)

2 Comments

I need in terms of data frame because there are some information that have to remain even the name are changed
@SasiwutChaiyadecha I've modified the code, hope it help you out.

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.