【问题标题】:string indices error while creating customize dictionary from data frame python从数据框python创建自定义字典时出现字符串索引错误
【发布时间】: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


    【解决方案1】:

    首先按boolean indexing过滤,然后按GroupBy.size按组计数,最后转换Seriesto_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()
    

    【讨论】:

    • 嗨@Jezrael 给定的数据框实际上是smaple 我有很多行数据我应该把你的代码行放在循环中还是分开?能否请您指教。
    • @RajeshMhatre - 不确定是否理解,但我的代码是你的(我希望它返回与真实数据相同的输出)
    • 我试过你的代码,但它说 name 'lst_code' is not defined 在哪里为 lst_code 赋值?
    • @RajeshMhatre - 顺便说一句,如果想要过滤缺失值,最好使用df.dropna(subset=['Code'])
    • 嘿,@Jezrael 谢谢我明白了,创建 lst_code 只是因为我在循环它。在您的代码中,它不是必需的。所以最终答案将是comp_dict = df.groupby('code')['Desc'].apply(list).to_dict()
    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多