pandas 熊猫将时间列添加到日期索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41530413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:44:44  来源:igfitidea点击:

Pandas adding Time column to Date index

pythonpandasmultiple-columnsreshapetimedelta

提问by alexbk66

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

我有一个数据框,日期索引类型是Timestamp,时间列是datetime.Time

            Time  Value
Date
2004-05-01  0:15  3.58507  
2004-05-02  0:30  3.84625
              ...

How do I convert it to:

我如何将其转换为:

                    Value
Date
2004-05-01 0:15     3.74618
2004-05-01 0:30     3.58507
2004-05-01 0:45     3.30998

I wrote a code which does work, but it's not very pythonic:

我写了一个确实有效的代码,但它不是很pythonic:

ind = frame.index.get_level_values(0).tolist()
tms = frame['Time']
new_ind = []
for i in range(0, len(ind)):
    tm = tms[i]
    val = ind[i] + timedelta(hours=tm.hour, minutes=tm.minute, seconds=tm.second)
    new_ind.append(val)

frame.index = new_ind
del frame['Time']

采纳答案by jezrael

You can first convert column Timeto_timedelta, then add to index, dropcolumn Timeand if necessary set index name:

您可以先转换 column Timeto_timedelta,然后添加到index, dropcolumnTime并在必要时设置索引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 Timeis datetime.timefor me works cast to stringfirst (if necessary add :00):

如果列Timedatetime.time我的作品string首先投射(如有必要,添加: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