我想将输出保存在json文件中。我有一个包含100行和20个项目列的数据框,其中一个列名称为ID
。在代码的某些部分中,我定义了函数
def function1(dataframe, ID):
df_sum = dataframe.sum()
df_sum = df_sum .sort_values(ascending=False)
df_sum = pd.DataFrame(df_sum , columns=['num_%s'%ID])
result_sum = df_sum .to_json(orient='columns')
return result_sum
然后,我的代码跟随
for num in list(dataframe.['ID'].values):
...some code lines, to drop and merge columns, which create the...
...dataframe df_aux
values = function1(df_aux, ID)
print(values)
输出为(编号在ID的[0,1,...,99]列表中)
{"num_1":{"item1":4}}
{"num_2":{"item19":6,"item20":4,"item18":4}}
...
{"num_99":{"item18":5,"item21":4,"item20":1}}
现在,我通过以下方式添加json转储功能
for num in list(dataframe.['ID'].values):
...some code lines, to drop and merge columns, which create the...
...dataframe df_aux
values = function1(df_aux, ID)
print(values)
with open('data.json', 'w') as outfile:
json.dump(values, outfile)
但是前面的代码仅返回最后的结果。当我打开data.json
文件时,它仅显示"{"num_99":{"item18":5,"item21":4,"item20":1}}"
然后我需要将所有值保存在json文件中。我是python的新手。任何提示将不胜感激。谢谢!
答案 0 :(得分:0)
您得到的只是最后一行,因为您在for循环的每次迭代中都覆盖了该值。
您可以做的是声明一个名为values
的数组并附加每个值。像这样:
values = []
for num in list(dataframe.['ID'].values):
# some code lines, to drop and merge columns, which create the
# dataframe df_aux
value.append( function1(df_aux, ID) )
with open('data.json', 'w') as outfile:
json.dump(values, outfile)