gpt4 book ai didi

python - 根据条件计算某个值在 pandas 数据框中出现的次数

转载 作者:行者123 更新时间:2023-12-02 18:44:49 25 4
gpt4 key购买 nike

我正在尝试计算某个值在数据框中的特定位置出现的次数。

作为示例,我使用此数据框:

   import pandas as pd

d = {'Fruit': ['Apple', 'Apple', 'Apple', 'Onion', 'Onion', 'Onion', 'Onion', 'Pear', 'Pear', 'Pear',
'Pear', 'Pear'],
'Country': ['USA', 'SUI', 'USA', 'SUI', 'USA', 'SUI', 'SUI', 'USA', 'USA', 'USA', 'SUI', 'SUI']}

df = pd.DataFrame(data=d)

我不明白如何计算例如美国和苏伊士有多少个苹果,并将其添加到“计数”列中。

输出应如下所示:

import pandas as pd

d = {'Fruit': ['Apple', 'Apple', 'Apple', 'Onion', 'Onion', 'Onion', 'Onion', 'Pear', 'Pear', 'Pear', 'Pear', 'Pear'],
'Country': ['USA', 'SUI', 'USA', 'SUI', 'USA', 'SUI', 'SUI', 'USA', 'USA', 'USA', 'SUI', 'SUI'],
'Count': [2, 1, 2, 3, 1, 3, 3, 3, 3, 3, 2, 2]}

df = pd.DataFrame(data=d)

我知道如何计算值本身(“水果”列中出现了多少个苹果),但不知道如何将此条件添加到计算中。

感谢您提前提供的帮助。

最佳答案

尝试Groupby transform :

df['counts'] = df.groupby(['Fruit', 'Country'])['Country'].transform('size')

df:

    Fruit Country  counts
0 Apple USA 2
1 Apple SUI 1
2 Apple USA 2
3 Onion SUI 3
4 Onion USA 1
5 Onion SUI 3
6 Onion SUI 3
7 Pear USA 3
8 Pear USA 3
9 Pear USA 3
10 Pear SUI 2
11 Pear SUI 2

关于python - 根据条件计算某个值在 pandas 数据框中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67587760/

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