我有一个产品清单,我想看看使用熊猫将两种产品组合售出的情况。

Date    Product   Price

1/1/19   Laptop    $700
1/1/19   Laptop    $700
1/1/19   iPhone    $500
1/1/19   Beats     $250
1/1/19   iPhone    $500
1/2/19   iPhone    $500
1/2/19   Beats     $250
1/2/19   Laptop    $700
1/3/19   Beats     $150
1/3/19   Laptop    $700
1/3/19   iPhone    $500
1/3/19   Beats     $250


这只是示例数据,但是我想看看Beats和iPhone在哪个日期比笔记本电脑获得更多的合并收入,以及使用Pandas的具体日期。任何帮助表示赞赏!

最佳答案

您可以尝试以下


>>> df['ProductGroup'] = (df.Product == 'Laptop').replace({True : "Laptop", False : "Iphone & Beats" })
>>> df
         Date Product  Sale    ProductGroup
0  2019-01-01  Laptop   700          Laptop
1  2019-01-01  Laptop   700          Laptop
2  2019-01-01  iPhone   500  Iphone & Beats
3  2019-01-01   Beats   250  Iphone & Beats
4  2019-01-01  iPhone   500  Iphone & Beats
5  2019-01-02  iPhone   500  Iphone & Beats
6  2019-01-02   Beats   250  Iphone & Beats
7  2019-01-02  Laptop   700          Laptop
8  2019-01-03   Beats   150  Iphone & Beats
9  2019-01-03  Laptop   700          Laptop
10 2019-01-03  iPhone   500  Iphone & Beats
11 2019-01-03   Beats   250  Iphone & Beats




>>> df.groupby(['Date', 'ProductGroup']).sum().unstack().droplevel(0, axis=1)
ProductGroup  Iphone & Beats  Laptop
Date
2019-01-01              1250    1400
2019-01-02               750     700
2019-01-03               900     700




>>> x[x['Iphone & Beats'] > x['Laptop']]
ProductGroup  Iphone & Beats  Laptop
Date
2019-01-02               750     700
2019-01-03               900     700

10-05 23:24
查看更多