【问题标题】:Why dataframe exports only last value of iteration to csv? (Python)为什么数据框仅将迭代的最后一个值导出到 csv? (Python)
【发布时间】:2021-09-22 07:30:32
【问题描述】:

我将结果从数据框导出到 CSV,但它只导出迭代的最后一个值。请检查我的代码并让我知道我在哪里做错了。感谢您的支持。

from pyswmm import Simulation, LidGroups, Nodes
from pyswmm.swmm5 import SWMMException
import os
import pandas as pd



output_path = "E:\VARS_Research\pyswmm_master\Test_Model\Test_Model_Manual"
output_csv_file = "node_flow.csv"

with Simulation('Test_model_LID.inp') as sim:
    nodes = Nodes(sim)
    
    for step in sim:
        j1 = Nodes(sim)["J1"]
        j2 = Nodes(sim)["J2"]
        j3 = Nodes(sim)["J3"]
        j4 = Nodes(sim)["J4"]
        results = {j1.total_inflow, j2.total_inflow, j3.total_inflow, j4.total_inflow} 
        sim.step_advance(300)
        
        for i in results:
            current_time = sim.current_time
            my_df = pd.DataFrame.from_dict({'j1': [j1.total_inflow], 'j2': [j2.total_inflow], 'j3': [j3.total_inflow], 'j4': [j4.total_inflow]})
            my_df.to_csv(os.path.join(output_path, "node_flow.csv"))

【问题讨论】:

    标签: python pandas dataframe csv


    【解决方案1】:

    results 的每次迭代中,您写入 csv 文件会覆盖前一个文件。不确定这是否是您想要的,但请在 to_csv() 中指定 mode='a'。默认模式为w

    Link to docs for to_csv()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多