【问题标题】:select pandas dataframe between two given dates where values from two columns are equal在两个给定日期之间选择熊猫数据框,其中两列的值相等
【发布时间】:2017-02-01 10:58:37
【问题描述】:

我可以通过首先将 datetime created 列设置为索引并对数据框进行切片来在两个日期之间选择 pandas 数据框。但现在我想做一个涉及额外日期时间列“修改日期”的新查询,即:

df = df.set_index(['created'])
print (df)
                        name      modifieddate
created                                                        
2014-01-01 16:07:07     john      2014-01-01 16:07:07
2014-01-04 16:07:07     harold    2014-01-04 16:07:07
2014-01-04 16:07:07     clara     2014-01-04 18:07:07
2014-01-05 16:07:07     emily     2014-01-06 16:07:07
2014-01-08 16:07:07     smiths    2014-01-08 16:07:07
2014-01-09 20:07:07     clara     2014-01-09 20:07:07
2014-01-10 18:07:07     clara     2014-01-10 18:07:07
2014-01-10 16:07:07     john      2014-01-11 16:07:07

选择createdmodifieddate 相等且位于给定日期时间2014-01-04 16:07:072014-01-10 16:07:07 之间的行:

                        name      modifieddate
created                                                        
2014-01-04 16:07:07     harold    2014-01-04 16:07:07 
2014-01-08 16:07:07     smiths    2014-01-08 16:07:07
2014-01-09 20:07:07     clara     2014-01-09 20:07:07

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以将betweenboolean indexing 一起使用:

    s = '2014-01-04 16:07:07'
    e = '2014-01-10 16:07:07'
    df = df[(df.index.to_series().between(s,e)) & 
            (df.modifieddate.between(s,e)) & 
            (df.index == df.modifieddate)]
    print (df)
                           name        modifieddate
    created                                        
    2014-01-04 16:07:07  harold 2014-01-04 16:07:07
    2014-01-08 16:07:07  smiths 2014-01-08 16:07:07
    2014-01-09 20:07:07   clara 2014-01-09 20:07:07
    

    【讨论】:

      【解决方案2】:

      假设您的列 'created' 不是索引。

       df2=     df.ix[(df.created==df.modifieddate)&(df.created>=datetime.datetime(2014,1,4,
       16,7,7))&(df.created <=datetime.datetime(2014,1,10, 16,7,7)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-08
        • 2021-12-14
        • 1970-01-01
        • 2015-08-15
        • 2015-08-09
        相关资源
        最近更新 更多