【问题标题】:Pandas: Accessing data with list of dates and DateTimeIndexPandas:使用日期列表和 DateTimeIndex 访问数据
【发布时间】:2018-02-07 06:20:38
【问题描述】:

我有一个带有 DateTimeIndex 的 pandas DataFrame:

                           A          B
2016-04-25 18:50:06   440.967796   201.049600  
2016-04-25 18:50:13   441.054995   200.767034  
2016-04-25 18:50:20   441.142337   200.484475
...
2016-07-27 18:50:06   440.967796   201.049600  
2016-07-27 18:50:13   441.054995   200.767034  
2016-07-27 18:50:20   441.142337   200.484475

我想使用日期列表提取给定日期yyyy-mm-dd 的所有数据:['2016-04-25','2016-04-28',...]

我尝试了以下方法:

 df[df.index.isin(['2016-04-25', '2016-04-26'])]

 Empty DataFrame

我想检索此列表中给定日期的所有数据(全天数据)

【问题讨论】:

    标签: python pandas dataframe datetimeindex


    【解决方案1】:

    您需要先通过this solutions 删除次数:

    df = df[df.index.normalize().isin(['2016-04-25', '2016-04-26'])]
    

    df = df[df.index.floor('D').isin(['2016-04-25', '2016-04-26'])]
    

    另一种解决方案是比较DatetimeIndex.date,但必须使用numpy.in1d 而不是isin

    df = df[np.in1d(df.index.date, pd.to_datetime(['2016-04-25', '2016-04-26']).date)]
    

    或者比较DatetimeIndex.strftime创建的字符串:

    df = df[np.in1d(df.index.strftime('%Y-%m-%d'), ['2016-04-25', '2016-04-26'])]
    

    print (df)
                                  A           B
    2016-04-25 18:50:06  440.967796  201.049600
    2016-04-25 18:50:13  441.054995  200.767034
    2016-04-25 18:50:20  441.142337  200.484475
    

    【讨论】:

    • 谢谢。我有一个后续问题。是否可以在不复制任何数据的情况下切断每一天的第一个n 数据行?日子有不同的开始/结束时间和不同的数据行数
    • 嗯,试试 df = df.drop(df.groupby(df.index.date).head(2).index) - 它从每个日期中删除前 2 个值。
    猜你喜欢
    • 2015-02-25
    • 2016-11-23
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 2019-09-20
    • 2016-11-04
    • 2015-10-28
    相关资源
    最近更新 更多