【发布时间】:2020-08-05 17:58:01
【问题描述】:
我有一个数据框,例如:
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)
鉴于错误,我相信我调用了空列表的第一个元素。但我无法修复它。我想保留这个功能(并升级它)请大家:)
【问题讨论】:
-
@ALollz 谢谢 :) 我也用你的评论更新了我的问题
标签: python pandas while-loop