簡體   English   中英

獲取 df 中幾個值的最小值和最大值

[英]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_itime (以秒為單位)。

首先,我想計算在最后一次看到和下一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 循環?

謝謝 !

無循環

  1. 生成一個新列,該列是公共汽車在停靠站的時間集(假設索引是連續的)
  2. 從這個得到第一次和最后一次。 然后構造一個第一次/最后一次的列表。 加上 180 秒以上的計算。 這個邏輯看起來很奇怪。 stop_1 只有一次訪問,因此強制計數 1 for > 180s
  3. 終於得到你想要的字典。
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM