【问题标题】:How can I join columns by DatetimeIndex, matching day, month and hour from data from different years?如何按 DatetimeIndex 加入列,从不同年份的数据中匹配日、月和小时?
【发布时间】:2020-07-29 21:09:48
【问题描述】:
我有一个具有 2019 年气象特征的数据集,我想将 2017 年和 2018 年的两列电力消耗数据集加入其中。我想按小时、日和月来匹配它们,但数据属于不同的年份。我该怎么做?
meteo 数据集是一个 6 列的类似数据框,其日期时间索引属于 2019。
【问题讨论】:
标签:
python
pandas
dataframe
group-by
datetimeindex
【解决方案1】:
您可以从索引中添加 3 个表示小时、日和月的列,并将它们用于以后的连接。 DatetimeIndex 具有时间戳不同部分的属性:
import pandas as pd
ind = pd.date_range(start='2020-01-01', end='2020-01-20', periods=10)
df = pd.DataFrame({'number' : range(10)}, index = ind)
df['hour'] = df.index.hour
df['day'] = df.index.day
df['month'] = df.index.month
print(df)
number hour day month
2020-01-01 00:00:00 0 0 1 1
2020-01-03 02:40:00 1 2 3 1
2020-01-05 05:20:00 2 5 5 1
2020-01-07 08:00:00 3 8 7 1
2020-01-09 10:40:00 4 10 9 1
2020-01-11 13:20:00 5 13 11 1
2020-01-13 16:00:00 6 16 13 1
2020-01-15 18:40:00 7 18 15 1
2020-01-17 21:20:00 8 21 17 1
2020-01-20 00:00:00 9 0 20 1