[英]Get all max and min values from df.groupby.().size() result
[英]get min and max values of several values in a df
我有這個 df :
df=pd.DataFrame({'stop_i':['stop_0','stop_0','stop_0','stop_1','stop_1','stop_0','stop_0'],'time':[0,10,15,50,60,195,205]})
每條線對應於公共汽車在stop_i
的time
(以秒為單位)。
首先,我想計算在最后一次看到和下一stop_i
一次看到之間有180 seconds
時間內巴士在stop_i
次數。 結果將是{'stop_0' : 2,'stop_1': 1}
因為對於stop_0
上一次第一次看到它是在15s
然后它再次出現在195s
所以195-15<=180
然后它計數for 2 和stop_1
只出現一次
其次,我想得到這個 dict : {'stop_0' : [[0,15],[195,205], 'stop_1': [[50,60]]}
包含總線時間的最小值和最大值在stop_i
有沒有辦法用熊貓來避免通過 df 循環?
謝謝 !
無循環
df=pd.DataFrame({'stop_i':['stop_0','stop_0','stop_0','stop_1','stop_1','stop_0','stop_0'],'time':[0,10,15,50,60,195,205]})
dfp =(df
# group when a bus is at a stop
.assign(
grp=lambda dfa: np.where(dfa["stop_i"].shift()!=dfa["stop_i"], dfa.index, np.nan)
)
.assign(
grp=lambda dfa: dfa["grp"].fillna(method="ffill")
)
# within group get fisrt and last time it's at stop
.groupby(["stop_i","grp"]).agg({"time":["first","last"]})
.reset_index()
# based on expected output... in reality there is only 1 time bus is between stops
# > 180 seconds. stop_1 only has one visit to cannot be > 180s
.assign(
combi=lambda dfa: dfa.apply(lambda r: [r[("time","first")], r[("time","last")]] , axis=1),
stopchng=lambda dfa: dfa[("stop_i")]!=dfa[("stop_i")].shift(),
timediff=lambda dfa: dfa[("time","first")] - dfa[("time","last")].shift(),
)
)
# first requirement... which seems wrong
d1 = (dfp.loc[(dfp[("timediff")]>=180) | dfp[("stopchng")], ]
.groupby("stop_i")["stop_i"].count()
.to_frame().T.reset_index(drop="True")
.to_dict(orient="records")
)
# second requirement
d2 = (dfp.groupby("stop_i")["combi"].agg(lambda s: list(s))
.to_frame().T.reset_index(drop=True)
.to_dict(orient="records")
)
print(d1, d2)
輸出
[{'stop_0': 2, 'stop_1': 1}] [{'stop_0': [[0, 15], [195, 205]], 'stop_1': [[50, 60]]}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.