首页 > 解决方案 > 我无法将整个循环的结果保存到 excel 中,而只能保存最后一次迭代

问题描述

我想将整个迭代的结果保存到一个 excel 文件中,但目前我只保存最后一次运行。为什么会发生这种情况以及如何解决?我添加了一行“追加”,但随后我收到一条错误消息..

path = '../'
df1=[]

for file in os.listdir(path):
 if file.endswith('.txt'):
     with open(os.path.join(path, file)) as f:
         df = pd.read_csv(f, sep="\t", header=0,usecols=[0,11])
         df.columns = ["x", "y"]

         abs_PAR=[]
         mean1=[]

         for (x, y) in df.iteritems():

          abs_PAR = sum(y.iloc[49:350]) / len(y.iloc[49:350])

          mean1.append(abs_PAR)

          newrow = {0:abs_PAR}
          df1 = df1.append(newrow)
          print(newrow)

writer = ExcelWriter('df1.xlsx')
df1.to_excel(writer,'Sheet1',index=False)
writer.save()

错误消息:AttributeError:“NoneType”对象没有“附加”属性

先感谢您

标签: pandasdataframeloopsappend

解决方案


不应将赋值运算符 (=) 与 append 一起使用。尝试改变

df1 = df1.append(newrow)

df1.append(newrow)

推荐阅读