我有一个数据帧,例如:
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我想用以下内容填充字典:-key:我们枚举字典中的键的数量(在本例中是从1到3)-value:'Id‘(也就是。索引)。
对于本例,所需的输出为:{'1': ['505', '258', '260'], '2':['263', '559', '586'], '3':['111','476']}
数据帧已经按“Ticket”列进行了排序,我希望它保持这种状态。为什么?我希望能够使用字典和数据帧(仍然由‘Ticket’排序)来找出字典中的任何ID是否与数据帧中其他位置的名称序列相关联。我希望我说清楚了!
我已经写了下面的代码,但我得到以下错误:“IndexError:单一位置索引器越界”。
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)考虑到这个错误,我相信我调用的是一个空列表的第一个元素。但我修不好它。
现在我知道还有其他更有效的方法来解决这个问题,但我想知道为什么这个函数不起作用?干杯:)
发布于 2020-04-23 02:09:15
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]}https://stackoverflow.com/questions/61372066
复制相似问题