我是一名 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 = None
。 index
,小写,已在数据帧循环中使用来引用数据帧中的索引值,因此即使大写的 Index
变量不会冲突,您也应该命名它别的东西。
关于Python - 通过 pandas 数据帧迭代并分配和有条件更新日期时间变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38363359/