Adding loop results as rows in dataframe - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Adding loop results as rows in dataframe (/thread-26673.html) |
Adding loop results as rows in dataframe - Shreya10o - May-09-2020 How do I make this for loop print the results as respective rows of the same dataframe. I tried this code but it doesn't seem to be working. list2=[(('ATM',), ('ROA',)), (('ATM',), ('ROE',)), (('ATM',), ('NIM',)), (('ATM',), ('ROA', 'ROE'))] tm_final = {0: 3, 1: 6, 2: 4, 3: 2, 4: 0} totalrows=sum(tm_final[i]>0 for i in tm_final) df=pd.DataFrame(columns=['A','B','C']) for i in tm_final: if tm_final[i]>0: for j in range(totalrows): df.iloc[j,0]=i df.iloc[j,1]=str(list2[i]) df.iloc[j,2]=tm_final[i] print(df) RE: Adding loop results as rows in dataframe - anbu23 - May-09-2020 Are you expecting this output? list2=[(('ATM',), ('ROA',)), (('ATM',), ('ROE',)), (('ATM',), ('NIM',)), (('ATM',), ('ROA', 'ROE'))] tm_final = {0: 3, 1: 6, 2: 4, 3: 2, 4: 0} totalrows=sum(tm_final[i]>0 for i in tm_final) df=pd.DataFrame(columns=['A','B','C']) for i in tm_final: if tm_final[i]>0: df=df.append({'A':i,'B':list2[i],'C':tm_final[i]},ignore_index=True) print(df) RE: Adding loop results as rows in dataframe - Shreya10o - May-09-2020 (May-09-2020, 10:25 AM)anbu23 Wrote: Are you expecting this output? Thank you! That worked. Only thing is that the print(df) should be out of the loop, so that it only prints it once.
|