gpt4 book ai didi

pandas - python Pandas : Count number of times each unique value appears for multiple columns

转载 作者:行者123 更新时间:2023-12-04 23:55:06 25 4
gpt4 key购买 nike

假设我有一个 DataFrame,例如,

In [7]: source = pd.DataFrame([['amazon.com', 'correct', 'correct'], ['amazon.com', 'incorrect', 'correct'], ['walmart.com', 'incorrect', 'correct'], ['walmart.com', 'incorrect', 'incorrect']], columns=['domain', 'price', 'product'])

In [8]: source
Out[8]:
domain price product
0 amazon.com correct correct
1 amazon.com incorrect correct
2 walmart.com incorrect correct
3 walmart.com incorrect incorrect

我要数,对于每个 domain ,次数 price == 'correct'price == 'incorrect' , 和 product 相同.换句话说,我希望看到这样的输出,
        domain      key      value  count
0 amazon.com price correct 1
1 amazon.com price incorrect 1
2 amazon.com product correct 2
3 walmart.com price incorrect 2
4 walmart.com product correct 1
5 walmart.com product incorrect 1

我该怎么做呢?

最佳答案

嵌套的应用程序会做到这一点

In [24]: source.groupby('domain').apply(lambda x: 
x[['price','product']].apply(lambda y: y.value_counts())).fillna(0)

Out[24]:
price product
domain
amazon.com correct 1 2
incorrect 1 0
walmart.com correct 0 1
incorrect 2 1

关于pandas - python Pandas : Count number of times each unique value appears for multiple columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17756984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com