我有一个数据集,其中包含一个处理(A,B,C组),并且我每组循环一个函数。然后,我想将此循环的输出保存到一个新的数据集中,在这里称为NewList。 但是,当我打开excel文件时,我只会得到新数据框的最后一列。如果我在python中打印新数据框,则可以看到所有行。对于处理(i)中的每个组,新的数据帧应具有y(s_1)。将文件保存在excel中时,我不明白我在做什么错。预先谢谢你!
import as np
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
# old dataframe
df = {'treatment': ['A', 'A', 'A', 'B', 'B', 'B'],
..}
###### function
def derivative (t):
slope =(-fit_B*fit_n*np.exp(-fit_n*t)) - (k*fit_m*np.exp(-fit_m*t))
return slope
###### loop function in dataset based on treatment
for i, g in df.groupby('treatment'):
y = derivative(t=10)
s_1 = pd.DataFrame([y])
###### new data frame
new_row = {'treatment': i, 'y': s_1.iloc[0, 0]}
new_dataframe = pd.DataFrame(new_row, index=[0])
#I tried to set the index = i, but it did not help.
NewList = new_dataframe.append(new_row, ignore_index=True)
### why do I get only the last line of the loop in the excel file? I am respecting the loop structure
writer = ExcelWriter('filename.xlsx')
NewList.to_excel(writer, 'Sheet1', index=False)
writer.save() ```