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

标签 python python-3.x pandas dataframe

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

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

   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/

相关文章:

python - 使用Python进行网页抓取时如何计算缩写列表的长度

python - 如何导入具有复杂字段的csv

python - TypeError : write() argument must be str, 不是字节,升级到 python 3

python - 从 python 中的数据帧矩阵打印标题值

python - DataFrame.set_index 返回 'str' 对象不可调用

python - 我的菜谱搜索程序(守护进程)的图像缓存循环出错

python - 如何使用 SqlAlchemy 进行 upsert?

python - Matplotlib 查看后自动关闭绘图/图形

python - 如何使用新名称(使用 for)在数据框中为每次迭代添加新列? Python

parsing - 如何加快pandas read_csv的速度?