我正在与DEAP合作开发遗传算法。 我在日志中得到了一些结果。 日志的形状是字典的附件,如下所示。
{"gen": 0, "nevals": 200, "avg": 5678.124656362589, "std": 1665.10303246997, "min": 2414.709605862963, "max": 10544.10349270114, "time": 3.061805009841919}
{"gen": 1, "nevals": 200, "avg": 4615.100755434814, "std": 1032.0542912118117, "min": 2414.709605862963, "max": 8710.009719746668, "time": 5.24877405166626}
{"gen": 2, "nevals": 200, "avg": 4426.86753960162, "std": 952.752217081577, "min": 2414.709605862963, "max": 7834.360961929298, "time": 7.716948747634888}
{"gen": 3, "nevals": 200, "avg": 4312.832205468258, "std": 954.6308089644021, "min": 2820.0828681777357, "max": 8069.475022854921, "time": 10.185122013092041}
{"gen": 4, "nevals": 200, "avg": 4333.539783185404, "std": 1155.0262921447736, "min": 2761.1404825322666, "max": 9830.868579904474, "time": 12.684537410736084}
{"gen": 5, "nevals": 200, "avg": 4285.034002752331, "std": 1136.5306484499206, "min": 2571.9258380478823, "max": 10371.549396541837, "time": 15.215197086334229}
我可以使用json.dumps
方法将其写为文本文件。但是我想像下面这样将其写为文本文件,与控制台上的结果相同。
我可以处理吗?
我现在使用python 3.6。
答案 0 :(得分:0)
您可以使用pandas
创建一个DataFrame并将其写入CSV文件。
In [1]: import pandas as pd
In [2]: from deap import tools
In [3]: logbook = tools.Logbook() # Creating a logbook
In [4]: logbook.record(gen=0, nevals=200, avg=5678.124656362589, std=1665.10303246997,
min=2414.709605862963, max=10544.10349270114, time=3.061805009841919)
In [5]: logbook.record(gen=1, nevals=200, avg=4615.100755434814, std=1032.0542912118117,
min=2414.709605862963, max=8710.009719746668, time=5.24877405166626)
In [6]: logbook.record(gen=2, nevals=200, avg=4426.86753960162, std=952.752217081577,
min=2414.709605862963, max=7834.360961929298, time=7.716948747634888)
In [7]: df_log = pd.DataFrame(logbook)
In [8]: df_log
Out[8]:
avg gen max min nevals std time
0 5678.124656 0 10544.103493 2414.709606 200 1665.103032 3.061805
1 4615.100755 1 8710.009720 2414.709606 200 1032.054291 5.248774
2 4426.867540 2 7834.360962 2414.709606 200 952.752217 7.716949
In [9]: df_log.to_csv('/path/to/your/file.csv', index=False) # Writing to a CSV file