python - 获取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 循环?
谢谢 !
解决方案
没有循环
- 生成一个新列,该列是公共汽车停靠的时间集(假设索引是连续的)
- 从这里得到第一次和最后一次。然后构造一个第一次/最后一次的列表。加上计算> 180s。这个逻辑似乎很奇怪。stop_1 只有一次访问,因此 > 180s 的计数为 1 是强制的
- 最后得到你想要的字典。
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]]}]
推荐阅读
- ruby - 查找记录的关联计数 > n
- python - cant change a symbol in every row from indexes list in Data Frame
- angular10 - 调试 Angular 10 项目时,我在 chrome windows 中没有 webpack 文件夹
- netlogo - NetLogo 中方向的平均值和标准差(以度为单位)
- python - 在python中解析excel并重建逻辑
- excel - 通过函数调用的变量返回零
- c# - 如何提取字符串二,一个在括号之间,两个不在括号中?
- mysql - 如何使用带有 where 子句的返回数据库对象在 node.js 中映射?
- matrix - 如何手动将协方差矩阵转换为相关矩阵?
- swift - SSH 连接到 SwiftUI 中的服务器