【问题标题】:Excel with multiple column indices and header rows into a Python dictionary via pandas通过 pandas 将具有多个列索引和标题行的 Excel 放入 Python 字典
【发布时间】:2019-08-19 15:42:46
【问题描述】:

我正在使用 Pyomo,我正在尝试为某些参数输入一些 4-D 数据。

我的 Excel 电子表格中的数据如下所示:

Image

原始数据的链接可以在这里找到:

Link to spreadsheet

我想在 Python 中导入数据,并将元组中的每个列索引和标题值作为字典的键,将值作为字典的值。

基本上,预期的输出应该是这样的:

p = {('Heat', 'Site 1', 1, 1): 14,
     ('Heat', 'Site 1', 1, 2): 16,
     ('Heat', 'Site 1', 1, 3): 10,
     ('Heat', 'Site 1', 2, 1): 13,
     ('Heat', 'Site 1', 2, 2): 13,
     ('Heat', 'Site 1', 2, 3): 13,
     ('Cool', 'Site 1', 1, 1): 5,
     ('Heat', 'Site 1', 1, 2): 6,
...
     ('Elec', 'Site 2', 2, 1): 11,
     ('Elec', 'Site 2', 2, 2): 15,
     ('Elec', 'Site 2', 2, 3): 15}

我的想法是先使用 pandas 导入 excel 文件,然后使用to_dict 方法。

我所做的如下:

import pandas as pd
Loads = pd.read_excel("Time_series_parameters.xlsx", index_col=[0,1], header = [0,1])

效果很好,我可以得到一个包含两个索引列和两个标题行的数据框:

       Heat   Cool   Elec   Heat   Cool   Elec
Time Site 1 Site 1 Site 1 Site 2 Site 2 Site 2
1 1      14      5     13     10     20     14
  2      16      6     11     10     14     10
  3      10      7     14     11     18     11
2 1      13      8     14     20     19     11
  2      13      7     11     14     15     15
  3      13      6     13     12     19     15

但是,我从那里尝试达到预期结果的任何尝试都失败了...to_dict 方法中的所有设置都没有给我预期的结果。

因此,如果有人可以在这里提供帮助,我将不胜感激。

【问题讨论】:

  • 在pandas中读取数据后,能否请您在代码引号中发布数据?
  • 刚刚做了,谢谢评论!

标签: python excel pandas pyomo


【解决方案1】:

我的解决方案是:

import pandas as pd
Loads = pd.read_excel("Time_series_parameters.xlsx", index_col=[0, 1], header=[0, 1])

out = {}
for index, inner in Loads.iteritems():
    for sec_index, value in inner.iteritems():
        out[index[0], index[1], sec_index[0], sec_index[1]] = value

结果输出是:

{('Heat', 'Site 1', 1, 1): 14,
 ('Cool', 'Site 1', 1, 1): 5,
 ('Elec', 'Site 1', 1, 1): 13,
 ('Heat', 'Site 2', 1, 1): 10,
 ('Cool', 'Site 2', 1, 1): 20,
 ('Elec', 'Site 2', 1, 1): 14,
 ('Heat', 'Site 1', 1, 2): 16,
 ('Cool', 'Site 1', 1, 2): 6,
 ('Elec', 'Site 1', 1, 2): 11,
 ('Heat', 'Site 2', 1, 2): 10,
 ...

【讨论】:

  • 是的,这行得通,这也是一个非常简洁的答案!谢谢!
  • 很高兴它有帮助,如果它有用,你可以投票给答案:)
  • 我投了赞成票,但我的声誉仍然很低,我的赞成票已计入但尚不可见:/
  • 没错,我忘了这个 :D 祝你的项目好运!
【解决方案2】:

我还找到了另一个答案,它使用其他一些 pandas 功能基本上可以达到相同的结果。代码如下:

Loads = pd.read_excel("Time_series_parameters.xlsx", sheet_name = "Loads", index_col=[0,1], header=[0, 1])
Loads = Loads.stack().stack()
Loads = Loads.reorder_levels([3,2,0,1])
p = Loads.to_dict()

输出再次看起来像这样:

{('Cool', 'Site 1', 1, 1): 18,
 ('Elec', 'Site 1', 1, 1): 18,
 ('Heat', 'Site 1', 1, 1): 19,
 ('Cool', 'Site 2', 1, 1): 17,
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 2022-08-18
    • 2020-08-18
    • 2020-02-21
    • 2019-01-05
    • 2022-01-07
    • 2014-07-10
    • 2022-11-14
    相关资源
    最近更新 更多