我有这个函数。
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)
这个函数的目的是通过有序的数据框架 将支付相同价格的人按照 “Ticket’id “的顺序排列在一起。(我不只是想把所有付了同样价格的人都列在一起,不管顺序如何!)
数据框架。
Price Ticket
Id
521 93.5000 12749
821 93.5000 12749
584 40.1250 13049
648 35.5000 13213
633 30.5000 13214
276 77.9583 13502
628 77.9583 13502
766 77.9583 13502
435 55.9000 13507
578 55.9000 13507
457 26.5500 13509
588 79.2000 13567
540 49.5000 13568
48 7.7500 14311
574 7.7500 14312
369 7.7500 14313
我测试的时候
same_price(df[:11])
工作得很好,输出是:{0: [521, 821], 1: [276, 628, 766], 2: [435, 578]}
但是。
same_fare(df[:10]) throws:
IndexError:单位置索引器出界。
我想知道这个函数有什么问题各位。
谢谢
解决方案:
我发现了问题所在,如果有人感兴趣的话……
df.iloc[n]
得到数据框架的(n+1)行。但是……我发现了问题所在,如果有人有兴趣的话……得到数据框的(n+1)行。shape[0]=n
意味着数据框有n个元素。
因此,我们使用 if n+1>df.shape[0]:
而不是 if n>df.shape[0]:
干杯:)