推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
livc
0D
V2EX  ›  Python

pandas 中如何让一列日期减去同一个日期?

  •  
  •   livc ·
    livc · Sep 1, 2016 · 5514 views
    This topic created in 3729 days ago, the information mentioned may be changed or developed.
                time loc
    0  2014-12-08 18  ad
    1  2014-12-09 12  as
    2  2014-12-12 12  xs
    

    处理为

      time loc
    0    1  ad
    1    2  as
    2    5  xs
    

    其中 "2014-12-08 18" 代表 14 年 12 月 8 日的 18 点,想把时间这列更新为从12 月 8 日算起的第X天,应该如何操作?

    9 replies  •  2018-04-09 17:42:39 +08:00
    aaronzjw
    aaronzjw
    Sep 1, 2016
    1
    import time 应该可以吧
    20150517
    20150517
    Sep 2, 2016 via iPhone
    2
    apply
    wickila
    wickila
    Sep 2, 2016❤️1
    3
    import pandas as pd
    import datetime


    def date2day(x):
    sd = datetime.datetime.strptime('2014-12-08 0', '%Y-%M-%d %H')
    d = datetime.datetime.strptime(x['time'], '%Y-%M-%d %H')
    x['time'] = (d - sd).days + 1
    return x


    df = pd.DataFrame([['2014-12-08 18', 'ad'], ['2014-12-09 12', 'as'], ['2014-12-12 12', 'xs']], columns=['time', 'loc'])
    df = df.apply(date2day, axis=1)

    print df
    xixijun
    xixijun
    Sep 2, 2016
    4
    df['date_diff']=df['time'].diff().fillna(0)+pd.Timedelta('1 days')
    livc
    livc
    OP
    Sep 2, 2016
    5
    @wickila 请问是否有更快的方法?这个函数处理 300 万的数据在我的 mac 上跑了 8 分钟…
    livc
    livc
    OP
    Sep 2, 2016
    6
    @wickila 重大 bug 。。。把 sd 改成 11 月 8 日,输出了负值。。
    livc
    livc
    OP
    Sep 2, 2016
    7
    @wickila 月份占位符应该小写。
    wickila
    wickila
    Sep 2, 2016
    8
    @livc 多谢指正。效率的话,只能小幅度地优化 date2day 函数,不过提升的效率应该有限。看看有没有大神有其他办法。
    weimao
    weimao
    Apr 9, 2018
    9
    td = _df['time']
    time = pd.to_datetime(td)
    start = pd.datetime(2014, 12, 8)
    day = time - start
    _df['time'] = day.dt.days
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4077 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 03:53 · PVG 11:53 · LAX 19:53 · JFK 22:53
    ♥ Do have faith in what you're doing.