[英]Compare date range in python dataframe
我在 pandas.core.indexes.datetimes.DatetimeIndexDatetimeIndex 中有一个日期范围:
(['2021-03-21', '2021-03-22', '2021-03-23', '2021-03-24',
'2021-03-25', '2021-03-26', '2021-03-27', '2021-03-28',
'2021-03-29', '2021-03-30', '2021-03-31', '2021-04-01',
'2021-04-02', '2021-04-03', '2021-04-04'],
dtype='datetime64[ns]', freq='D')
此外系列数据为:
2021-03-27 2
2021-03-28 1
2021-03-30 1
2021-03-31 2
2021-04-04 3
现在,如果我想获得一个包含所有日期及其相反值的数据框,并且如果缺少任何日期,它应该将该日期作为 0 值给出答案。 输出格式应为:
2021-03-22 0
2021-03-23 0
2021-03-24 0
2021-03-25 0
2021-03-26 0
2021-03-27 2
2021-03-28 1
...
IIUC 使用Series.reindex
,只需要Series
DatetimeIndex
来匹配idx
:
idx = pd.DatetimeIndex(['2021-03-21', '2021-03-22', '2021-03-23', '2021-03-24',
'2021-03-25', '2021-03-26', '2021-03-27', '2021-03-28',
'2021-03-29', '2021-03-30', '2021-03-31', '2021-04-01',
'2021-04-02', '2021-04-03', '2021-04-04'])
print (s)
2021-03-27 2
2021-03-28 1
2021-03-30 1
2021-03-31 2
2021-04-04 3
Name: a, dtype: int64
s.index = pd.to_datetime(s.index)
s = s.reindex(idx, fill_value=0)
print (s)
2021-03-21 0
2021-03-22 0
2021-03-23 0
2021-03-24 0
2021-03-25 0
2021-03-26 0
2021-03-27 2
2021-03-28 1
2021-03-29 0
2021-03-30 1
2021-03-31 2
2021-04-01 0
2021-04-02 0
2021-04-03 0
2021-04-04 3
Name: a, dtype: int64
如果想通过date_range
重新索引而不是idx
使用它:
s = s.reindex(pd.date_range('2021-03-21', '2021-04-04', freq='D'), fill_value=0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.