gpt4 book ai didi

python - 从数据框python创建自定义字典时出现字符串索引错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:15:12 24 4
gpt4 key购买 nike

我正在尝试从数据框创建字典,下面是数据框和代码:

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']}

请建议我该如何解决这个问题?

最佳答案

首先按 boolean indexing 过滤然后按 GroupBy.size 每组计数, 最后转换 Series to_dict :

lst_code = 'NA'
comp_dict = df[df['Code'] != lst_code].groupby('Code')['Desc'].apply(list).to_dict()
print (comp_dict)
{'SE': ['Cycle', 'Train'], 'XS': ['Train', 'Car']}

如果不需要过滤:

comp_dict = df.groupby('code')['Desc'].apply(list).to_dict()

关于python - 从数据框python创建自定义字典时出现字符串索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52829448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com