【发布时间】: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