【问题标题】:appending a list to a set of a result (dict)将列表附加到一组结果(dict)
【发布时间】:2021-06-07 21:02:58
【问题描述】:

我正在为一些工作准备代码。我有一个如下所示的数据框:

# initialize list of lists 
data = [['1', 10, 50, 'ev', 'CA'], ['2', 15, 40, 'ev', 'CA'], ['3', 14, 60, 'ev', 'CN']] 
  
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['person_id', 'kwh', 'distance', 'type', 'country']) 
  
# print dataframe. 
df 

然后我循环遍历df 的每一行,以便根据一列数据框进行计算。

dics = []
for i, row in df.iterrows():
    # Retrieve person-ID
    person = df['person_id'].tolist()
    if row['type'] == 'ev':
        cm.array.loc['Small','BEV','electricity consumption',:] = [[row['kwh_km']]]
        ---Some very long codes---
        output = results.sel(impact_category='cc', year=2020, size='Small', value=0)\
        .to_dataframe('impact') #selecting only cc
        output_dict = dict(zip(['ex', 'ne', 'ec',
                      'ma', 'gl', 'eo', 'po', 
                      'es', 'ro'], output.impact)) 
        dics.append({person: {output_dict}})   #assigning person id to each result in a dict

问题:我尝试获取列表person_id,在代码末尾,我尝试在output_dict 中创建结果字典。 现在我有一个列表和一个字典,我想将它们附加到dics,但它对我不起作用。它抛出了一个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-164-da106d6e5fc2> in <module>
     19                       'ma', 'gl', 'eo', 'po',
     20                       'es', 'ro'], output.impact))
---> 21         dics.append({person: {output_dict}})

TypeError: unhashable type: 'dict'

我希望输出如下所示(示例):output_dict 根据数据框中的每个 person_id

[{'1':{'ex': 0.0,
  'ne': 0.0,
  'ec': 0.0,
  'ma': 0.0,
  'gl': 0.0,
  'eo': 0.0,
  'po': 0.0,
  'es': 0.0,
  'ro': 0.0}},
 {'2':{'ex': 0.0,
  'ne': 0.0,
  'ec': 0.0,
  'ma': 0.0,
  'gl': 0.0,
  'eo': 0.0,
  'po': 0.0,
  'es': 0.0,
  'ro': 0.0}},
 {'3':{'ex': 0.0,
  'ne': 0.0,
  'ec': 0.0,
  'ma': 0.0,
  'gl': 0.0,
  'eo': 0.0,
  'po': 0.0,
  'es': 0.0,
  'ro': 0.0}}]

很抱歉,我删除了“一些非常长的代码”中的一些代码。非常感谢您的帮助和建议。提前谢谢你。

【问题讨论】:

    标签: python arrays list dataframe


    【解决方案1】:

    看起来您正在创建将一个人的 id 附加到一组结果,而不是一个 id 到结果。

    output_dict 周围的花括号表示您正在创建一组字典。由于字典不是可散列的,python 会引发错误。如果您想将 dics 保留为单个条目字典的列表,删除这些花括号应该可以解决您的问题。

    dics.append({person: output_dict})
    

    但是,它可能会更好地将dics 设置为字典,以便您可以将所有 id 和结果存储在同一个地方,如下所示:

    {'1':{'ex': 0.0,
      'ne': 0.0,
      'ec': 0.0,
      'ma': 0.0,
      'gl': 0.0,
      'eo': 0.0,
      'po': 0.0,
      'es': 0.0,
      'ro': 0.0},
     '2':{'ex': 0.0,
      'ne': 0.0,
      'ec': 0.0,
      'ma': 0.0
      'gl': 0.0,
      'eo': 0.0,
      'po': 0.0,
      'es': 0.0,
      'ro': 0.0)
      ...
    }
    

    这将使您能够更简单地提取结果。在您最初尝试提取 id 1 的 persion 的结果时,您需要在列表中找到该条目,然后将数据从字典中提取出来:

    for data in dics:
        if data.keys()[0] == "1":
            result = data["1"]
            # do something with result
    

    这是非常冗长和缓慢的。但是通过将它们存储为单个字典,您可以立即访问它们:

    result = dics["1"]
    
    dics = dict()
    
    # some code here...
    dics[person] = output_dict
    

    【讨论】:

    • 感谢您的建议,但是当我使用索引时,它会抛出另一个错误:TypeError: list indices must be integers or slices, not list
    • 哦,您想要一份单项词典列表吗?然后在没有花括号的情况下追加将正常工作。我会更新答案
    • 是的,但实际上,我之前确实尝试过,但语法无效。这就是为什么我添加两个花括号
    • 但是如果我删除一对花括号,错误仍然存​​在:TypeError: unhashable type: 'list'.
    • 您将 person 定义为不可散列的 list,将其转换为单个 id 或其他可散列类型。字典基本上只是一个set,其元素具有另一个关联值。字典键必须是可散列的
    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 2018-08-15
    • 2012-03-10
    • 2013-08-07
    • 2020-02-25
    • 1970-01-01
    • 2021-01-11
    相关资源
    最近更新 更多