V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
V2EX  ›  Python

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

  •  
  •   livc ·
    livc · 2016-09-01 23:39:35 +08:00 · 4131 次点击
    这是一个创建于 2785 天前的主题,其中的信息可能已经有所发展或是发生改变。
                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 条回复    2018-04-09 17:42:39 +08:00
    aaronzjw
        1
    aaronzjw  
       2016-09-01 23:49:29 +08:00
    import time 应该可以吧
    20150517
        2
    20150517  
       2016-09-02 03:58:10 +08:00 via iPhone
    apply
    wickila
        3
    wickila  
       2016-09-02 09:39:53 +08:00   ❤️ 1
    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
        4
    xixijun  
       2016-09-02 10:29:28 +08:00
    df['date_diff']=df['time'].diff().fillna(0)+pd.Timedelta('1 days')
    livc
        5
    livc  
    OP
       2016-09-02 12:21:18 +08:00
    @wickila 请问是否有更快的方法?这个函数处理 300 万的数据在我的 mac 上跑了 8 分钟…
    livc
        6
    livc  
    OP
       2016-09-02 12:39:02 +08:00
    @wickila 重大 bug 。。。把 sd 改成 11 月 8 日,输出了负值。。
    livc
        7
    livc  
    OP
       2016-09-02 12:50:56 +08:00
    @wickila 月份占位符应该小写。
    wickila
        8
    wickila  
       2016-09-02 15:27:44 +08:00
    @livc 多谢指正。效率的话,只能小幅度地优化 date2day 函数,不过提升的效率应该有限。看看有没有大神有其他办法。
    weimao
        9
    weimao  
       2018-04-09 17:42:39 +08:00
    td = _df['time']
    time = pd.to_datetime(td)
    start = pd.datetime(2014, 12, 8)
    day = time - start
    _df['time'] = day.dt.days
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5397 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 08:23 · PVG 16:23 · LAX 01:23 · JFK 04:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.