python 将值保存在 Dataframe 中并替换为csv格式

aelbi1ox  于 2022-12-10  发布在  Python
关注(0)|答案(1)|浏览(180)

所以我不太清楚如何表达这个问题,因为我对pythong和一般的编码都很陌生。我有一个GUI,它可以从csv:

def updatetext(self):
    """adds information extracted from database already provided"""

    df_subj = Content.extract_saved_data(self.date)

    self.lineEditFirstDiagnosed.setText(str(df_subj["First_Diagnosed_preop"][0])) \
        if str(df_subj["First_Diagnosed_preop"][0]) != 'nan' else self.lineEditFirstDiagnosed.setText('')
    self.lineEditAdmNeurIndCheck.setText(str(df_subj['Admission_preop'][0])) \

效果很好
现在,如果我在GUI中更改值,我希望它们在csv中更新。我是这样开始的:

def onClickedSaveReturn(self):
    """closes GUI and returns to calling (main) GUI"""

    df_general = Clean.get_GeneralData()

    df_subj = {k: '' for k in Content.extract_saved_data(self.date).keys()} # extract empty dictionary
    df_subj['ID'] = General.read_current_subj().id[0]
    df_subj['PID'] = df_general['PID_ORBIS'][0]
    df_subj['Gender'] = df_general['Gender'][0]
    df_subj['Diagnosis_preop'] = df_general['diagnosis'][0]

    df_subj["First_Diagnosed_preop"] = self.lineEditFirstDiagnosed.text()
    df_subj['Admission_preop'] = self.lineEditAdmNeurIndCheck.text()
    df_subj['Dismissal_preop'] = self.DismNeurIndCheckLabel.text()

我的老板现在补充说:

subj_id = General.read_current_subj().id[0] # reads data from curent_subj (saved in ./tmp)
df = General.import_dataframe('{}.csv'.format(self.date), separator_csv=',')
if df.shape[1] == 1:
    df = General.import_dataframe('{}.csv'.format(self.date), separator_csv=';')

idx2replace = df.index[df['ID'] == subj_id][0]

# TODO: you need to find a way to turn the dictionaryy df_subj into a dataframe and replace the data at
#  the index idxreplace of 'df' with df_subj. Later I would suggest to use line 322 to save everything to the
#  file
df.iloc[idx2replace] = pds.DataFrame([df_subj])
df.to_csv("preoperative.csv", index=False)
# df.to_csv(os.path.join(FILEDIR, "preoperative.csv"), index=False)

self.close()

我真的不知道该如何处理这个问题,或者说,老实说,我根本不知道该怎么做。
希望有人能帮我。
谢谢你

h7appiyu

h7appiyu1#

你应该只加载一次文件,并保留DF(self.df或其他)。然后显示它,每次用户在GUI中更改一个值时,DF应该更新,当用户点击保存时,你应该用内存中的当前DF覆盖现有文件。

相关问题