首页 > 解决方案 > 获取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]})

每条线对应于time公共汽车在的位置(以秒为单位)stop_i

首先,我想计算公共汽车在最后一次看到和下一次第一次看到之间stop_i有多少次。180 seconds结果将是{'stop_0' : 2,'stop_1': 1}因为stop_0第一次看到它的最后一次是在15s然后它再次出现在195s所以195-15<=180它计数为 2 并且stop_1只出现一次

其次,我想得到这个字典:{'stop_0' : [[0,15],[195,205], 'stop_1': [[50,60]]}包含公共汽车在stop_i

有没有办法用 pandas 来避免通过 df 循环?

谢谢 !

标签: pythonpython-3.xpandaslistdictionary

解决方案


没有循环

  1. 生成一个新列,该列是公共汽车停靠的时间集(假设索引是连续的)
  2. 从这里得到第一次和最后一次。然后构造一个第一次/最后一次的列表。加上计算> 180s。这个逻辑似乎很奇怪。stop_1 只有一次访问,因此 > 180s 的计数为 1 是强制的
  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]]}]

推荐阅读