按特定列查找表中所有对的计数

2024-04-25 19:10:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,上面有周、商店、品牌等列。例如

week shop brand
1    1    cola
1    2    sprite
1    3    pepsi
1    4    pepsi
2    1    cola 
2    2    sprite
2    3    sprite
2    4    sprite

我想知道每个星期有多少商店会遇到几个品牌 结果表为:

week brand1  brand2  num_shops
1    cola    sprite  1
1    cola    pepsi   2
1    sprite  cola    1
1    sprite  pepsi   1  
1    pepsi   cola    2
1    pepsi   sprite  1    
2    cola    sprite  3
2    sprite  cola    3

我知道我应该这么做

def func(x):
    x1 = x.merge(x,on=["week"],suffixes =('1','2'))
    x1.groupby(["brand1","brand2"]).apply(func1)
    return x1

def func1(x):
#make count

data.groupby(["week"]).apply(func)

如果我有很多数据,我能做得更快吗?你知道吗

编辑:店铺数栏组成如下:我们用一周时间。看看上面所有的品牌,我们看看有多少双重复。例如,我们首先得到如下表,然后得到关于num\u商店的信息:

week brand1  brand2 
1    cola    sprite  
1    cola    pepsi
1    cola    pepsi   
1    sprite  cola    
1    sprite  pepsi     
1    pepsi   cola
1    pepsi   cola    
1    pepsi   sprite      
2    cola    sprite  
2    cola    sprite  
2    cola    sprite  
2    sprite  cola
2    sprite  cola
2    sprite  cola    

Tags: 数据defnum商店funcapplyx1品牌
0条回答
网友
1楼 · 发布于 2024-04-25 19:10:24

使用^{}^{}筛选出两个brand中的相同值,然后使用^{}^{}计数:

df = (df.merge(df,on=["week"], suffixes= ('1','2'))
       .query("brand1 != brand2")
       .groupby(['week','brand1','brand2'], sort=False)
       .size()
       .reset_index(name='num_shops'))
print (df)
   week  brand1  brand2  num_shops
0     1    cola  sprite          1
1     1    cola   pepsi          2
2     1  sprite    cola          1
3     1  sprite   pepsi          2
4     1   pepsi    cola          2
5     1   pepsi  sprite          2
6     2    cola  sprite          3
7     2  sprite    cola          3

编辑:

您的解决方案应该更改:

def func(x):
    x1 = x.merge(x,on=["week"],suffixes =('1','2'))
    x1 = x1[x1['brand1'].ne(x1['brand2'])]
    return x1.groupby(["brand1","brand2"], sort=False).size()

df = df.groupby(["week"]).apply(func).reset_index(name='num_shops')
print (df)
   week  brand1  brand2  num_shops
0     1    cola  sprite          1
1     1    cola   pepsi          2
2     1  sprite    cola          1
3     1  sprite   pepsi          2
4     1   pepsi    cola          2
5     1   pepsi  sprite          2
6     2    cola  sprite          3
7     2  sprite    cola          3

相关问题 更多 >