【问题标题】:Pandas objet-list datetime serie to datetime index熊猫对象列表日期时间系列到日期时间索引
【发布时间】:2021-12-29 13:27:52
【问题描述】:

我正在使用 python-elasticsearch api 上的 fields 参数从 elasticsearch 检索一些数据,尝试解析 iso 格式的 @timestamp,以用于 pandas 数据帧。

fields = \
    [{
      "field": "@timestamp",
      "format": "strict_date_optional_time"
    }]

默认情况下,elasticsearch 以数组列表格式返回结果,如文档中所示:

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-fields.html

The fields response always returns an array of values for each field, even when there is a single value in the _source. 

因此,生成的数据帧包含一个无法通过常规方法解析为日期时间系列的对象列表系列。

Name: fields.@timestamp, Length: 18707, dtype: object
0       [2021-11-04T01:30:00.263Z]
1       [2021-11-04T01:30:00.385Z]
2       [2021-11-04T01:30:00.406Z]
3       [2021-11-04T01:30:00.996Z]
4       [2021-11-04T01:30:01.001Z]
                   ...            
8368    [2021-11-04T02:00:00.846Z]
8369    [2021-11-04T02:00:00.894Z]
8370    [2021-11-04T02:00:00.895Z]
8371    [2021-11-04T02:00:00.984Z]
8372    [2021-11-04T02:00:00.988Z]

尝试将系列解析为日期时间系列时:

pd.to_datetime(["fields.@timestamp"])

结果:

TypeError: <class 'list'> is not convertible to datetime

我的用例需要很多日期时间格式,并且字段参数非常适合查询多种格式,但是列出的对象日期时间字符串很难。

【问题讨论】:

    标签: python pandas dataframe datetime elasticsearch


    【解决方案1】:

    这里的问题是字段项。@timestamp 实际上是列表。

    所以你可以这样做:

    fields['timestamp'] = fields['timestamp'].str[0]
    

    从列表中提取日期, 然后使用 pd.to_datetime :

    fields['timestamp'] = pd.to_datetime(fields['timestamp'])
    

    【讨论】:

      猜你喜欢
      • 2019-02-19
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多