繁体   English   中英

通过基于2组仅选择两个值并将其余值转换为0来对Pandas组进行选择

[英]Pandas groupby selecting only two values based on 2 groups and converting rest to 0

这是从我在这里得到回答的问题开始的: Pandas group通过仅基于2个组选择一个值并将剩余的值转换为0

我有一个熊猫数据框,其日期时间索引如下所示:

df =

           Fruit    Quantity
01/02/10    Apple   4
01/02/10    Apple   6
01/02/10    Apple   12
01/02/10    Pear    7
01/02/10    Grape   8
01/02/10    Grape   5
02/02/10    Apple   2
02/02/10    Fruit   6
02/02/10    Pear    8
02/02/10    Pear    5
02/02/10    Apple   2
02/02/10    Apple   2

现在,对于每个日期和每个水果,我只希望两个值(最好是前两个),日期的其余水果保持为零。 因此,所需的输出如下:

           Fruit    Quantity
01/02/10    Apple   4
01/02/10    Apple   6
01/02/10    Apple   0
01/02/10    Pear    7
01/02/10    Grape   8
01/02/10    Grape   5
02/02/10    Apple   2
02/02/10    Fruit   6
02/02/10    Pear    8
02/02/10    Pear    5
02/02/10    Apple   2
02/02/10    Apple   0

这只是一个小例子,但我的主数据框有300万行以上,并且不一定按日期排序。

谢谢

做一个cumcount通过分组date(index)Fruit ,然后清零行,其中计数大于1

df['QuanityTrimmed'] = df.Quantity.where(df.groupby([df.index, df.Fruit]).cumcount() < 2, 0)

print(df)
#          Fruit  Quantity  QuanityTrimmed
#01/02/10  Apple         4               4
#01/02/10  Apple         6               6
#01/02/10  Apple        12               0
#01/02/10   Pear         7               7
#01/02/10  Grape         8               8
#01/02/10  Grape         5               5
#02/02/10  Apple         2               2
#02/02/10  Fruit         6               6
#02/02/10   Pear         8               8
#02/02/10   Pear         5               5
#02/02/10  Apple         2               2
#02/02/10  Apple         2               0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM