【问题标题】:Python - Iterrow through pandas dataframe and assign and conditionally update datetime variablePython - 遍历 pandas 数据框并分配和有条件地更新日期时间变量
【发布时间】:2016-11-16 17:32:19
【问题描述】:

我是 Python 新手,想知道是否有人可以帮助我。

我想遍历 pandas 数据框中的 datetime 列,同时为每次迭代更新一个具有最近时间的变量。假设这是我的数据:

    Time
06:12:50
06:13:51
06:13:51
06:13:50
06:14:51
06:14:49

对于我的结果,我希望它看起来像这样:

RecentTime:
   06:12:50
   06:13:51
   06:13:51
   06:13:51
   06:14:51
   06:14:51

我认为代码应该看起来像这样,但我遇到了麻烦,不知道为什么。这是我的代码:

RecentTime = [] # Store list of most recent time for each row
Index: None       # Create empty variable
# Loop through 
for index, row in data.iterrows():
    index = row['Time']   # Save value as index
    if index >= row['Time']: # If time is greater than current row
    index = row['Time']
        RecentTime.append(index) # Append most recent variable into list
    else:
        continue

出于某种原因,这是我的结果:

RecentTime
  06:12:50
  06:13:51
  06:13:51
  06:13:50
  06:14:51
  06:14:49

【问题讨论】:

  • 您通常不应使用 for 循环遍历数据帧。尝试弄清楚如何比较和子集,例如沿着these lines

标签: python loops datetime if-statement pandas


【解决方案1】:

每次通过循环时,您都会在检查不等式之前覆盖变量index,所以

if index >= row['Time']:

不仅总是True,而且在检查此不等式之前,您总是将索引设置为等于当前时间。根据您描述中所需结果时间永远不会早于上一行的模式,我认为您正在寻找更像这样的东西:

RecentTime = [] # Store list of most recent time for each row
priortime = None
# Loop through 
for index, row in data.iterrows():
    currenttime = row['Time']
    if priortime is None:
        priortime = currenttime

    if priortime > currenttime: # If prior time is greater than current row
        currenttime = priortime

    priortime = currenttime    
    RecentTime.append(currenttime)

最后,Index: None 行应该抛出错误SyntaxError: invalid syntax。假设您想为变量赋值,请使用Index = Noneindex,小写字母,已在数据帧循环中用于引用数据帧中的索引值,因此即使您的大写 Index 变量不会冲突,您也应该将其命名为其他名称。

【讨论】:

  • 是否可以包含一个参数来保留最新的currenttime 60 秒时间差内的行?
  • 是的,您可以使用 datetime.timedelta。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 2022-09-24
  • 2021-12-19
  • 2016-11-28
  • 2019-06-22
  • 1970-01-01
相关资源
最近更新 更多