【问题标题】:How to directly use Pandas Date-time index in calculations?如何在计算中直接使用 Pandas 日期时间索引?
【发布时间】:2013-08-24 11:24:22
【问题描述】:

我有以下有效的代码:

table['CALC_DOM']=table.index
table['CALC_DOM']=table['END_DATE']-['CALC_DOM']

难道不应该有更好的方法直接从 table.index 转换吗?喜欢:

table['CALC_DOM']=table.index
table['CALC_DOM']=table['END_DATE']-(table.index()) 

我尝试过使用
table.index.get_values

table.index.date

...但我得到的只是:
TypeError: incompatible type [object] for a datetime/timedelta operation

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    非常接近!

    In [1]: df = DataFrame(randn(5,2),index=date_range('20130101',periods=5))
    
    In [3]: df['date'] = Timestamp('20130102')
    
    In [4]: df
    Out[4]: 
                       0         1                date
    2013-01-01  2.406932 -0.313473 2013-01-02 00:00:00
    2013-01-02  0.034162 -0.708450 2013-01-02 00:00:00
    2013-01-03 -1.585031  0.587243 2013-01-02 00:00:00
    2013-01-04  1.454818  1.089208 2013-01-02 00:00:00
    2013-01-05 -0.778016 -0.994242 2013-01-02 00:00:00
    
    In [5]: df['td'] = df['date']-df.index.to_series()
    
    In [6]: df
    Out[6]: 
                       0         1                date                td
    2013-01-01  2.406932 -0.313473 2013-01-02 00:00:00  1 days, 00:00:00
    2013-01-02  0.034162 -0.708450 2013-01-02 00:00:00          00:00:00
    2013-01-03 -1.585031  0.587243 2013-01-02 00:00:00 -1 days, 00:00:00
    2013-01-04  1.454818  1.089208 2013-01-02 00:00:00 -2 days, 00:00:00
    2013-01-05 -0.778016 -0.994242 2013-01-02 00:00:00 -3 days, 00:00:00
    

    【讨论】:

    • 我会坚持下去,直到我明白为止!感谢大家的帮助!
    • 似乎很明显(但我无法理解)!
    • 旁注,我不认为 to_series 记录在索引中(在文档字符串或文档中也没有高度记录)?
    • 其实我现在想起来,它可以很容易地直接工作...hmmmm
    猜你喜欢
    • 2014-09-04
    • 2018-04-21
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    相关资源
    最近更新 更多