如何为数据帧中的不同日期重置时间

2024-04-26 10:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

根据下面的输入df,我需要在天一改变就将“TimeLeft”列的时间设置为00:00:00。例如

输入测向:

   TimeLeft              colum_B  ProgPerc  id_B      ts_B
0  2017-04-27T00:01:12   B        97.0      id1       2017-04-27T01:36:48
1  2017-04-27T00:00:12   B        98.0      id1       2017-04-27T01:37:48
2  2017-04-26T23:58:24   B        99.0      id1       2017-04-27T01:38:48
3  2017-04-26T23:57:45   B        100.0     id1       2017-04-27T01:39:36

输出测向:

   TimeLeft              colum_B  ProgPerc  id_B      ts_B
0  2017-04-27T00:01:12   B        97.0      id1       2017-04-27T01:36:48
1  2017-04-27T00:00:12   B        98.0      id1       2017-04-27T01:37:48
2  2017-04-26T00:00:00   B        99.0      id1       2017-04-27T01:38:48
3  2017-04-26T00:00:00   B        100.0     id1       2017-04-27T01:39:36

任何帮助都将不胜感激。事先谢谢你的帮助。致以最诚挚的问候,C


Tags: iddf时间ts问候id1columtimeleft
1条回答
网友
1楼 · 发布于 2024-04-26 10:32:54

问题解决了。以下是解决方案:

if __name__ == "__main__":
  filepath="/home/SERILOCAL/c.allocca/Desktop/MantaData/test1/1490022000_1.csv"
  df = pd.read_csv(filepath) #your input data saved here

  df["ts_B_day"]=df["ts_B"].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S").date().day)    
  df["TimeLeft_day"]=df["TimeLeft"].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S").date().day)    

 def replace_time(row): 
    date_=datetime.datetime.strptime(row['TimeLeft'], "%Y-%m-%dT%H:%M:%S").date()
    end_time = datetime.datetime.combine(date_, datetime.time(00, 00,00))
    end_time = end_time.strftime('%Y-%m-%dT%H:%M:%S')    
    return end_time

df['TimeLeft'] = df.apply(lambda row: replace_time(row) if row['ts_B_day'] != row['TimeLeft_day']  else (row['TimeLeft']), axis=1)
print(df.to_string())

相关问题 更多 >