【发布时间】: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