gpt4 book ai didi

python - 遍历 Pandas 数据框

转载 作者:太空狗 更新时间:2023-10-30 01:55:05 26 4
gpt4 key购买 nike

我有一个 pandas 数据框,其中一列表示另一列中的位置值是否在其下方的行中发生了变化。例如,

2013-02-05 19:45:00   (39.94, -86.159)     True
2013-02-05 19:50:00 (39.94, -86.159) True
2013-02-05 19:55:00 (39.94, -86.159) False
2013-02-05 20:00:00 (39.777, -85.995) False
2013-02-05 20:05:00 (39.775, -85.978) True
2013-02-05 20:10:00 (39.775, -85.978) True
2013-02-05 20:15:00 (39.775, -85.978) False
2013-02-05 20:20:00 (39.94, -86.159) True
2013-02-05 20:30:00 (39.94, -86.159) False

所以,我想做的是逐行浏览此数据框并检查带有 False 的行。然后(可以添加另一列)在那个地方花费的总“连续”时间。可以像上面的例子一样再次访问同一个地方。在这种情况下,它被视为一个单独的条件。所以,对于上面的例子,是这样的:

2013-02-05 19:45:00   (39.94, -86.159)     True    0
2013-02-05 19:50:00 (39.94, -86.159) True 0
2013-02-05 19:55:00 (39.94, -86.159) False 15
2013-02-05 20:00:00 (39.777, -85.995) False 5
2013-02-05 20:05:00 (39.775, -85.978) True 0
2013-02-05 20:10:00 (39.775, -85.978) True 0
2013-02-05 20:15:00 (39.775, -85.978) False 15
2013-02-05 20:20:00 (39.94, -86.159) True 0
2013-02-05 20:25:00 (39.94, -86.159) False 10

然后我将绘制这些每天使用 hist() 函数所花费的“连续”时间的直方图。我如何通过遍历数据框从第一个数据框获取第二个数据框?我是 python 和 pandas 的新手,真正的数据文件很大,所以我需要一些相当高效的东西。

最佳答案

再来一张

df['group'] = (df.condition == False).astype('int').cumsum().shift(1).fillna(0)

df
date long lat condition group
2/5/2013 19:45:00 39.940 -86.159 True 0
2/5/2013 19:50:00 39.940 -86.159 True 0
2/5/2013 19:55:00 39.940 -86.159 False 0
2/5/2013 20:00:00 39.777 -85.995 False 1
2/5/2013 20:05:00 39.775 -85.978 True 2
2/5/2013 20:10:00 39.775 -85.978 True 2
2/5/2013 20:15:00 39.775 -85.978 False 2
2/5/2013 20:20:00 39.940 -86.159 True 3
2/5/2013 20:25:00 39.940 -86.159 False 3

df['result'] = df.groupby(['group']).date.transform(lambda sdf: 5 *len(sdf))

df
date long lat condition group result
2/5/2013 19:45:00 39.940 -86.159 True 0 15
2/5/2013 19:50:00 39.940 -86.159 True 0 15
2/5/2013 19:55:00 39.940 -86.159 False 0 15
2/5/2013 20:00:00 39.777 -85.995 False 1 5
2/5/2013 20:05:00 39.775 -85.978 True 2 15
2/5/2013 20:10:00 39.775 -85.978 True 2 15
2/5/2013 20:15:00 39.775 -85.978 False 2 15
2/5/2013 20:20:00 39.940 -86.159 True 3 10
2/5/2013 20:25:00 39.940 -86.159 False 3 10

关于python - 遍历 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15683588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com