【发布时间】:2018-10-16 06:50:13
【问题描述】:
我正在尝试从数据框创建字典,下面是数据框和代码:
Code | Desc
XS | Train
XS | Car
SE | Cycle
SE | Train
下面是我的代码
lst_code = 'NA'
comp_list=[]
comp_dict = {}
for row in test_df:
if str(row['code']) != lst_code:
lst_code = row['code']
if comp_list:
comp_dict.update(lst_code,comp_list)
else:
comp_list.append(row['desc'])
使用上面的代码我得到以下错误
if str(row['analyst_code']) != lst_code:
TypeError: string indices must be integers
我期待下面的字典:
comp_dict = {'XS':['Train','Car'],
'SE':['Cycle','Train']}
请建议,我该如何解决这个问题?
【问题讨论】:
标签: python pandas dictionary dataframe