python - 处理具有可怕日期时间数据的数据集

标签 python datetime pandas numpy julian-date

我有一个巨大的传感器数据集并正在使用Python。问题在于它们的日期格式。基本上,这就是日期列的样子;

07/ 7/15 06:51

07/ 7/15 06:53

07/ 7/15 06:55

07/ 7/15 06:57

07/ 7/15 06:59

2015-07-07 07:00:46.047

07/ 7/15 07:03

07/ 7/15 07:05

07/ 7/15 07:07

07/ 7/15 07:09

07/ 7/15 07:11

07/ 7/15 07:13

2015-07-07 07:15:53.007

2015-11-14 23:33:43.000

2015-11-14 23:35:44.000

2015-11-14 23:37:43.000

2015-11-14 23:39:43.000

2015-11-14 23:41:43.000

11/14/15 23:42

2015-11-14 23:45:43.000

11/14/15 23:46

2015-11-14 23:49:43.000

2015-11-14 23:51:44.000

我将解析日期以使用工作日、周末,另外也许我会将它们转换为儒略日期格式(使用数字 1 到 365 而不是常规日期)。

我曾尝试过:

  • 在读取 csv 时解析日期

  • 解析器之前的日期;例如dateutil.parser.parse(x)

  • 日期时间.strptime

但它们都不起作用。我仍然无法解析日期。 这些数据分为 10 个 Excel 文件。

当我使用 pd.read_csv(......, parse_dates('date')) 读取它们时,它将日期列读取为 'object'某些文件为 'datetime64' 格式,而其他文件则为 'datetime64' 格式。但即使格式为 'datetime64' 日期的文件也无法解析并给出错误:

"Unknown String Format".

任何想法都会有所帮助!

最佳答案

如果我们假设所提供的格式是唯一使用的两种格式,则以下内容可能会起作用。只需以字符串形式读取数据,然后我们将从那里进行解析。

import pandas as pd

df = pd.DataFrame({'date': ['07/7/15 06:51', '07/7/15 06:59', '2015-07-07 07:00:46.047',
                            '11/14/15 23:42', '2015-11-14 23:45:43.000']})

# mask the df based on the date formats
dash_mask = df['date'].str.contains('-')
slash_mask = df['date'].str.contains('/')

# use the masks to apply pd.to_datetime() to only one format at a time
df.loc[dash_mask, 'datetime'] = pd.to_datetime(df.loc[dash_mask, 'date'],
                                               infer_datetime_format=True)
df.loc[slash_mask, 'datetime'] = pd.to_datetime(df.loc[slash_mask, 'date'],
                                               infer_datetime_format=True)

>>> df['datetime'].dt.date
0    2015-07-07
1    2015-07-07
2    2015-07-07
3    2015-11-14
4    2015-11-14

当然,这可以变成一个函数,并且可以使用类似的方法容纳更多的日期格式,但这应该可以完成工作。我承认它并不漂亮......

顺便说一句,如果您只关心日期而不关心一天中的时间,那么如果该部分在解析日期时引起问题,您可以将其删除。

df['only_date'] = df['date'].str.split(' ').str[0]
>>> df
                      date   only_date
0            07/7/15 06:51     07/7/15
1            07/7/15 06:59     07/7/15
2  2015-07-07 07:00:46.047  2015-07-07
3           11/14/15 23:42    11/14/15
4  2015-11-14 23:45:43.000  2015-11-14

关于python - 处理具有可怕日期时间数据的数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41380002/

相关文章:

c# - 这个 DateTime 字符串有什么问题?

c# - MySQL Connector/NET 的 MySqlCommand 不使用参数

php - DateTime::modify() 的表达式以更改月份中的日期

python - 如何为数据框中最后几行的 pandas 列定义条件?

python - 用优雅的 Pandas 代码替换迭代

python - 将 pandas 分组列转换为字符串时出错

python - 如何获取列表中所有 NaN 的所有索引?

python - 为什么 dnspython 模块会给出 LifetimeTimeout 错误?

python - 是否可以使用 Google Assistant 作为自制 Python 个人助理的基础?

python - 交换 numpy 数组中的两个值。