【问题标题】:Check if list of dates is complete in Python using Pandas使用 Pandas 检查 Python 中的日期列表是否完整
【发布时间】:2019-09-26 04:29:57
【问题描述】:

我有一个文本文件,其标题包含时间序列的开始日期和结束日期。文件的其余部分包含 3 列:开始日期、结束日期和值 - 如下所示。

19580101 20181231
19580101 19580131     4.2
19580201 19580228    -1.6
19580301 19580331    -4.9
.
.
.
20181001 20181031    -8.2
20181101 20181130    -3.8
20181201 20181231     3.1

我想在图表上显示一段时间内的值,但首先要检查日期是否完整。

这是我的代码的一部分:

import numpy as np
import pandas as pd

df = pd.read_fwf('file.txt',header=None)
head = df.loc[0] #extract header
df = df.drop(0) #delete first line

date_seq = pd.to_datetime(df.loc[:,0]) #convert column 0 to datetime

start_date = str(int(head[0])) #'19850101'
end_date = str(int(head[1])) #'20181231'

#synthesize date range:
strt = pd.to_datetime(start_date,format='%Y%m%d')
ends = pd.to_datetime(end_date,format='%Y%m%d')
date_rng = pd.date_range(start=strt, end=ends, freq='MS')

#compare extracted and synthesized date sequences:
diff = date_seq - date_rng
print diff.sum()

输出为:0天00:00:00

这似乎有些低效。有没有更优雅的方式?

【问题讨论】:

  • 您可以将日期时间设为索引,然后执行以下操作:pd.date_range(df.index.min(), df.index.max()).difference(df.index)跨度>

标签: python pandas date time-series


【解决方案1】:

您可以查看该系列的差异,而不是创建第二个系列。

df['date_check'] = df.date_col.diff()
df.date_check.value_counts()

这将为您提供系列中所有空白的列表。如果您的数据框中有多个系列,这也适用于 groupby

【讨论】:

    猜你喜欢
    • 2017-02-15
    • 2019-11-21
    • 1970-01-01
    • 2018-07-11
    • 2023-03-27
    • 2020-11-03
    • 2021-07-28
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多