推荐学习书目
› 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
KIDJourney
V2EX  ›  Python

请问,如何将这个 DataFrame 转换成我想要的样子呢?

  •  
  •   KIDJourney ·
    KIDJourney · Mar 31, 2016 · 3406 views
    This topic created in 3879 days ago, the information mentioned may be changed or developed.
    我现在有个 DateFrame
    index song_id action_type ds
    0 f87ff481d85d2f95335ab602f38a7655 1 20150315
    1 f87ff481d85d2f95335ab602f38a7655 2 20150315
    2 f87ff481d85d2f95335ab602f38a7655 1 20150315
    3 f87ff481d85d2f95335ab602f38a7655 3 20150316
    4 096e604f7b152fad0246ae731ed8ca73 1 20150315
    5 096e604f7b152fad0246ae731ed8ca73 1 20150315
    6 096e604f7b152fad0246ae731ed8ca73 2 20150315
    7 096e604f7b152fad0246ae731ed8ca73 1 20150316
    8 096e604f7b152fad0246ae731ed8ca73 2 20150316
    9 096e604f7b152fad0246ae731ed8ca73 1 20150316

    怎样才能让他变成
    song_id 20150315 20150316
    f87ff481d85d2f95335ab602f38a7655 [1:2,2:1,3:0] [1:0,2:0,3:1]
    096e604f7b152fad0246ae731ed8ca73 [1:2,2:1,3:0] [1:2,2:1,3:0]

    这样的呢?
    提前感谢大家。
    7 replies  •  2016-04-03 13:07:32 +08:00
    JamesRuan
    JamesRuan
    Mar 31, 2016
    1
    这不是反范式的吗?现在转换麻烦,日后要提取也麻烦。
    KIDJourney
    KIDJourney
    OP
    Mar 31, 2016
    2
    @JamesRuan
    感谢回复。
    我需要一个以 data series 为 columns 的训练集,感觉这样组织比较好。。。
    有什么更好的组织方式吗?
    timeship
    timeship
    Mar 31, 2016
    3
    银古桑
    JamesRuan
    JamesRuan
    Mar 31, 2016❤️1
    4
    @KIDJourney
    拆表啊,现在这个表是多对多的关系,你拆成多对一的关系用就好了。
    ruoyu0088
    ruoyu0088
    Apr 1, 2016❤️1
    5
    df.groupby(["song_id", "ds", "action_type"]).action_type.count().unstack().fillna(0).astype(int)
    KIDJourney
    KIDJourney
    OP
    Apr 3, 2016
    6
    @JamesRuan

    手动拆写完了,但是写起来又乱又麻烦。。。
    我想知道有没有属于 df 的优雅一点的处理方法。
    KIDJourney
    KIDJourney
    OP
    Apr 3, 2016
    7
    @ruoyu0088 十分感谢!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1047 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 23:09 · PVG 07:09 · LAX 15:09 · JFK 18:09
    ♥ Do have faith in what you're doing.