python - 然后 Groupby 检查行匹配并计算该值的并发实例数

标签 python pandas numpy

我有这个数据框

     car   color  years  max_years
0   audi   black      1          7
1   audi    blue      2          7
2   audi  purple      4          7
3   audi   black      6          7
4    bmw    blue      1          5
5    bmw    green     2          5
6    bmw    grey      5          5
7    bmw    blue     20          5
8   fiat   green      1          4
9   fiat   green      3          4
10  fiat   green      4          4
11  fiat   green     10          4

如果颜色条目为 1 年,我想计算该颜色在该汽车品牌组中出现的次数,直至该组的最大年数。

我想为每个汽车品牌组运行 isin 颜色条件,我认为我的问题是颜色列表不是 grouby('car') 并且因此评估适用于所有汽车

结果应该是:

0  audi       2
1   bmw       1
2  fiat       3

如有任何帮助,我们将不胜感激


import pandas as pd

car =  ['audi', 'audi', 'audi', 'audi', 'bmw', 'bmw', 'bmw', 'bmw', 'fiat', 'fiat', 'fiat', 'fiat']
color =  ['black', 'blue', 'purple', 'black', 'blue', 'green', 'grey', 'blue', 'green', 'green', 'green', 'green']
years = [1, 2, 4, 6, 1, 2, 5, 20, 1, 3, 4, 10, ]
max_years = [7, 7, 7, 7, 5, 5, 5, 5, 4, 4, 4, 4]

data = {'car': car, 'color': color, 'years': years, 'max_years': max_years}
df = pd.DataFrame(data=data)

colors =  df.loc[df.years == 1]['color'].values

colour_cars = df[(df.years <= df.max_years) & df['color'].isin(colors)].groupby(['car']).size().reset_index(name='colour_cars')

print(colour_cars)

最佳答案

想法是使用Series.mapSeries 使用经过过滤的 DataFrame 创建,其中 years == 1 并按列 color 进行比较:

colors =  df.loc[df.years == 1].set_index('car')['color']

df1 = (df[(df.years <= df.max_years) & df['car'].map(colors).eq(df['color'])]
         .groupby('car')
         .size()
         .reset_index(name='colour_cars'))
print(df1)

    car  colour_cars
0  audi            2
1   bmw            1
2  fiat            3

或者您可以使用 mask 通过 Series.view 转换为整数,然后需要通过 sum 计算 True 的值,并将 Series df['car'] 传递给 分组依据:

colors =  df.loc[df.years == 1].set_index('car')['color']

df1 = (((df.years <= df.max_years) & df['car'].map(colors).eq(df['color']))
         .view('i1')
         .groupby(df['car'])
         .sum()
         .reset_index(name='colour_cars'))
print(df1)

    car  colour_cars
0  audi            2
1   bmw            1
2  fiat            3

不同的想法是通过 GroupBy.transform 测试每组的第一个颜色使用 first (如果每个组的第一年总是 1,则解决方案有效):

df2 = (df[(df.years <= df.max_years)]
           .groupby('car')['color']
           .transform('first').eq(df['color'])
           .view('i1')
           .groupby(df['car'])
           .sum()
           .reset_index(name='colour_cars'))

print(df2)

    car  colour_cars
0  audi            2
1   bmw            1
2  fiat            3

关于python - 然后 Groupby 检查行匹配并计算该值的并发实例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59050317/

相关文章:

python - 使用 Pandas 按组获取计数

python - 来自 SQL 查询的 Pandas DataFrame : difference in dates is wrongly displayed

python - Groupby 一定数量的行 pandas

python - Numpy算术

python - 为什么我的 Python 异常没有被重新引发?

python - 在Scrapy(网络爬虫)中返回复杂的项目

python - 无法将元组转换为python中的列表

numpy - Numpy `where` 子句的奇怪行为

python - 将一个数据集中的值替换为另一个数据集中的值的有效方法

Python3 生产 : logging exceptions without using traceback module