获取df中多个值的最小值和最大值

2024-05-21 05:35:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个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_i180 seconds的时间。结果将是{'stop_0' : 2,'stop_1': 1},因为stop_0最后一次第一次看到它是在15s,然后它再次出现在195s,所以195-15<=180然后它计数为2,而stop_1只出现一次

其次,我想得到这个dict:{'stop_0' : [[0,15],[195,205], 'stop_1': [[50,60]]},其中包含总线在stop_i时的最小值和最大值

有没有一种方法可以避免通过df的回路

谢谢


Tags: 方法dataframedftime时间dictpd计数
1条回答
网友
1楼 · 发布于 2024-05-21 05:35:43

禁止循环

  1. 生成一个新列,该列是总线停止的时间集(假设索引是连续的)
  2. 从这里得到第一次和最后一次。然后构建第一次/最后一次的列表。加上>;180年代。这种逻辑似乎很奇怪。stop_1只有一次访问,因此>;计数为1;180年代是被迫的
  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]]}]

相关问题 更多 >