【发布时间】:2020-06-25 13:13:48
【问题描述】:
ElectricityDemand = []
FuelDemand = []
dict_of_results = {}
data = pd.read_csv('data.csv', sep = ';', index_col = False)
# data.csv looks like the following, containing 2 objects:
# parameter1;parameter2;parameter3
# 388;2000;14
# 293;1890;12.6
list_of_objects = [list(row) for row in data.values]
for item in range(len(list_of_objects)):
MyObject = Class(parameter1 = list_of_objects[item][0],
parameter2 = list_of_objects[item][1],
parameter3= list_of_objects[item][2])
# Load more datafiles and define some constants
# Iterating over every hour of a year and calculate the ElectricityDemand and FuelDemand of the object
for h in range(8760):
# ...calculate here...
ElectricityDemand.append(MyObject.electricity_demand)
FuelDemand.append.append(MyObject.fuel_demand)
results = pd.DataFrame({'ElectricityDemand': ElectricityDemand, 'FuelDemand': FuelDemand})
for i in range(len(list_of_objects)):
results['iter'] = i
dict_of_results[i] = results.copy()
该程序在一年中的几个小时(8760 小时)上进行迭代 - 请参阅内部循环 - 用于 2 个不同的对象(请参阅外部循环:range(len(list_of_objects)))。
我想将内部循环的结果存储为列表(ElectricityDemand 和 FuelDemand),然后存储在(临时)DataFrame(results)中,然后将 DataFrame 保存在字典中,然后继续对象 2 的程序相同。
在这个阶段,我得到一个包含 2 个 DataFrames 的字典,每个 DataFrames 有 17520 (8760*2) 个观察值。
我找不到我的错误...我怎样才能获得一个包含 2 个 DataFrame(每个都有 8760 个观察值)的字典?
我现在的输出:
dict_of_results
类型:字典
尺寸:2
值:{0:DataFrame, 1:DataFrame}
在 0:DataFrame
类型:数据帧
尺寸:(17520, 2)
值:列名:ElectricityDemand 和 FuelDemand
以及 ElectricityDemand 和 FuelDemand 的 17520 行(对象 1 的数据(来自输入数据 388;2000;14)和对象 2(来自输入数据 293;1890;12.6)) .
在 1:DataFrame 中
和 0:DataFrame 完全一样
我想要的输出: dict_of_results
类型:字典
尺寸:2
值:{0:DataFrame, 1:DataFrame}
在 0:DataFrame
类型:数据帧
尺寸:(8760, 2)
值:列名:ElectricityDemand 和 FuelDemand
和对象一的 8760 行(来自输入数据 388;2000;14)
在 1:DataFrame 中
与 0:DataFrame 中的不完全相同,但 Size: (8760, 2) ElectricityDemand 和 FuelDemand 以及第二个对象的相应行/值/结果(来自输入数据 293;1890;12.6) .
【问题讨论】:
-
在哪里初始化
ElectricityDemand和FuelDemand列表? -
@SergeBallesta 在第 1 行和第 2 行中,我为两者创建了空列表。随着内部循环的每次迭代,我使用计算结果增加这些列表。 FuelDemand 分别参见 ElectricityDemand.append(MyObject.electricity_demand)
-
@SergeBallesta 你能再帮忙吗?请参阅我对您的回答的评论...
标签: python pandas dataframe dictionary for-loop