Pandas adding Time column to Date index

前端 未结 1 1115
甜味超标
甜味超标 2021-01-18 00:53

I have a dataframe, Date index type is Timestamp, Time column is datetime.Time:

            Time  Value
Date
2004-05-01  0:15  3.58507  
20         


        
1条回答
  •  深忆病人
    2021-01-18 01:36

    You can first convert column Time to_timedelta, then add to index, drop column Time and if necessary set index name:

    df.Time = pd.to_timedelta(df.Time + ':00', unit='h')
    df.index = df.index + df.Time
    df = df.drop('Time', axis=1)
    df.index.name = 'Date'
    print (df)
                           Value
    Date                        
    2004-05-01 00:15:00  3.58507
    2004-05-02 00:30:00  3.84625
    

    If column Time is datetime.time for me works cast to string first (if necessary add :00):

    df.Time = pd.to_timedelta(df.Time.astype(str), unit='h')
    df.index = df.index + df.Time
    df = df.drop('Time', axis=1)
    df.index.name = 'Date'
    print (df)
                           Value
    Date                        
    2004-05-01 00:15:00  3.58507
    2004-05-02 00:30:00  3.84625
    

    0 讨论(0)
提交回复
热议问题