将循环结果添加为数据帧中的行

I am trying to 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. It is giving an index error right now because it outputs separate empty dataframes for each iteration.

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)

所需结果:

   A                B                             C
   0  (('ATM',), ('ROA',))                        3
   1  (('ATM',), ('ROE',))                        6
   2  (('ATM',), ('NIM',))                        4
   3  (('ATM',), ('ROA', 'ROE'))                  2
评论
怪我瞎i
怪我瞎i

Please check the tm_final it has 5 values instead of 4.

df=pd.DataFrame(columns=['A','B','C'])
df.A = tm_final.keys()
df.B = list2
df.C = tm_final.values()
df
   A                     B  C
0  0      ((ATM,), (ROA,))  3
1  1      ((ATM,), (ROE,))  6
2  2      ((ATM,), (NIM,))  4
3  3  ((ATM,), (ROA, ROE))  2
点赞
评论