本文介绍了 pandas 将“时间"列添加到“日期"索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

如何将其转换为:

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

我写了一个行得通的代码,但是它不是很pythonic:

I wrote a code which does work, but it's not very 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']

推荐答案

您可以先转换列Time to_timedelta ,然后添加到index drop Time,并在必要时设置索引name:

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

如果对我来说列Timedatetime.time,则首先将其转换为string(如有必要,请添加:00):

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

这篇关于 pandas 将“时间"列添加到“日期"索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 13:47