首页 > 解决方案 > While-loop/在数据框中查找序列

问题描述

我有一个数据框,例如:

                Price   Ticket
Id                            
505          86.5000  110152           
258          86.5000  110152           
760          86.5000  110152           
263          79.6500  110413           
559          79.6500  110413           
586          79.6500  110413           
111          52.0000  110465           
476          52.0000  110465           
431          26.5500  110564           
367          75.2500  110813           
171          33.5000  111240

我想用以下内容填充字典: - 键:我们枚举字典中的键数(在这种情况下从 1 到 3) - 值:'Id'(又名索引)。

对于此示例,所需的输出是:{'1': ['505', '258', '260'], '2':['263', '559', '586'], '3':['111','476']}

数据框已经按“票证”列排序,我希望它保持这种状态。为什么?我希望能够使用字典和数据框(仍按“票”排序)来确定字典中的任何 ID 是否与数据框中其他地方的名称序列相关联。我希望我清楚!

我已经编写了下面的代码,但出现以下错误:'IndexError: single positional indexer is out-of-bounds'。

def same_price(df=df):
    df= df.sort_values(by='Ticket')
    nucleus= dict()
    k=0
    while df.shape[0]>=2:
        if df.Price.iloc[0]==df.Price.iloc[1]:
            value= df.Price.iloc[0]
            n=0
            nucleus[k]= []
            while df.Price.iloc[n]==value:
                nucleus[k].append(df.index[n])
                n+=1
                if n>df.shape[0]:
                    df.drop(nucleus[k], axis=0, inplace=True)
                    break 
            else:
                df.drop(nucleus[k], axis=0, inplace=True)
                k+=1       
        else:
            if df.shape[0]>=3: 
                df.drop(df.index[0], axis=0, inplace=True)
            else:
                break
    return(nucleus)

鉴于错误,我相信我调用了空列表的第一个元素。但我无法修复它。

现在我知道还有其他更有效的方法可以解决问题,但我想了解为什么这个功能不起作用?干杯:)

标签: pythonpandaswhile-loop

解决方案


IIUC,您可以使用groupby.apply(list)

df.index.to_series().groupby(df.Ticket.factorize()[0] + 1).apply(list).to_dict()

输出:

{1: [505, 258, 760],
 2: [263, 559, 586],
 3: [111, 476],
 4: [431],
 5: [367],
 6: [171]}

推荐阅读