【问题标题】:Pivot table using Python Pandas, unit price an sum使用 Python Pandas 的数据透视表,单价总和
【发布时间】:2013-12-05 20:11:44
【问题描述】:

我想使用 py-pandas 从此类数据中生成数据透视表

id      product  credit
1        book      -5
1        ipad     -15
1      server     -25
2        book      -5
15      server     -25
2       glass      -2
2       glass      -2
1        book      -5
15       glass      -2
1         car    -150

到 那种电子表格

id        1          2        15
---------------------------------
book     -5 (2)     -5(1)     NA
ipad     -15(1)      NA       NA
server   -25(1)      NA      -25(1)
glass     NA        -2(2)    -2(1)
car       -150(1)    NA       NA

这会将 id 显示为列,产品显示为行,单位信用和购买的产品数量。

感谢您的帮助

-H

【问题讨论】:

    标签: python python-2.7 pandas pivot


    【解决方案1】:

    主要思想是使用pandas...pivot_table()

    如果您只想sum 您的数据,那么np.sum 可以:

    >>> df.pivot_table(cols='id', values='credit', rows='product', aggfunc=np.sum)
    id        1   2   15
    product             
    book     -10  -5 NaN
    car     -150 NaN NaN
    glass    NaN  -4  -2
    ipad     -15 NaN NaN
    server   -25 NaN -25
    

    或者您可以使用collections.Counter 获取接近您需要的格式的数据(Counter 的性能不是很好,所以要小心这个):

    >>> from collections import Counter
    >>> df.pivot_table(cols='id', values='credit', rows='product', aggfunc=Counter)
    id              1        2         15
    product                              
    book       {-5: 2}  {-5: 1}       NaN
    car      {-150: 1}      NaN       NaN
    glass          NaN  {-2: 2}   {-2: 1}
    ipad      {-15: 1}      NaN       NaN
    server    {-25: 1}      NaN  {-25: 1}
    

    或者定义自定义函数来得到你所需要的:

    >>> from collections import defaultdict
    >>> def hlp_count(x):
    ...     d = defaultdict(int)
    ...     for v in x:
    ...         d[v] += 1
    ...     # join in case you have more than one distinct price
    ...     return ', '.join(['{0} ({1})'.format(k, v) for k, v in d.iteritems()])
    
    >>> df.pivot_table(cols='id', values='credit', rows='product', aggfunc=hlp_count)
    id             1       2        15
    product                           
    book       -5 (2)  -5 (1)      NaN
    car      -150 (1)     NaN      NaN
    glass         NaN  -2 (2)   -2 (1)
    ipad      -15 (1)     NaN      NaN
    server    -25 (1)     NaN  -25 (1)
    

    【讨论】:

    • 谢谢!太棒了。
    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 2019-06-28
    • 2020-11-24
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多