【问题标题】:Store DataFrame in a dictionary within two for-loops将 DataFrame 存储在两个 for 循环内的字典中
【发布时间】: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) .

【问题讨论】:

  • 在哪里初始化ElectricityDemandFuelDemand 列表?
  • @SergeBallesta 在第 1 行和第 2 行中,我为两者创建了空列表。随着内部循环的每次迭代,我使用计算结果增加这些列表。 FuelDemand 分别参见 ElectricityDemand.append(MyObject.electricity_demand)
  • @SergeBallesta 你能再帮忙吗?请参阅我对您的回答的评论...

标签: python pandas dataframe dictionary for-loop


【解决方案1】:

您在循环之前初始化 ElectricityDemandFuelDemand 列表,然后在循环内附加到它们。在第二遍时,它们仍然包含第一遍中的行。

您应该将这两个变量都设置为循环内的新列表:

...
for item in range(len(list_of_objects)):
    ElectricityDemand = []  
    FuelDemand = []
    ...

【讨论】:

  • 很抱歉(迟到的)回调,但毕竟解决方案不起作用!我在 for item in range(len(list_of_objects)): 之后初始化了列表,但最后我得到了一个包含 2 个数据帧的字典,每个数据帧的大小为 (8760, 3),这很好 (2+ 1 个变量,因为迭代),但都具有第二个对象的计算结果!!
猜你喜欢
  • 2018-04-12
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2022-11-17
  • 2021-05-19
  • 2017-05-09
  • 2019-07-16
相关资源
最近更新 更多