如何重置Dataframe中不同日期的时间

时间:2017-09-15 20:41:23

标签: python pandas dataframe

考虑到下面的输入df,我需要将时间设置为列#00; TimeLeft"一天改变。例如,

输入df:

   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

输出df:

   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

1 个答案:

答案 0 :(得分:0)

解决了问题。这是解决方案:

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())