Python - 通过 pandas 数据帧迭代并分配和有条件更新日期时间变量

标签 python loops datetime if-statement pandas

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

我想迭代 pandas 数据框中的日期时间列,同时为每次迭代更新最近时间的变量。假设这是我的数据:

    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

最佳答案

每次循环时,您都会在检查不等式之前写入变量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 变量不会冲突,您也应该命名它别的东西。

关于Python - 通过 pandas 数据帧迭代并分配和有条件更新日期时间变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38363359/

相关文章:

javascript - 对将函数应用于所有 li 项目感到困惑

javascript - JavaScript for 循环中的 jQuery 不起作用

Python:如何将字符串转换为日期时间

Python - 提取最里面的列表

python - Shapely MultiLinestring 在 Pyplot 中显示为 MultiPolygon

ipython 并行的 Python namespace 问题

java - 在 JDBC 中将时间戳存储为 Long .. 好还是坏?

python - 如何检索列表中的 n 项组

将字符从源字符串复制到缓冲区 - C

java - 无法在 Android Studio 上将 DateTime 插入 SQLite