Python 获取数据框中出现次数最多的类别对
Python get pairs of categories that appears the most in a dataframe
鉴于下面的 table 是数据集,给出了数据集的 4 列和前 14 行,但有超过 10,000 行。在一个订单中有多个产品被卖给客户。
我想知道,在所有订单中,哪对产品类别出现的次数最多?示例(Cat1 和 Cat2)
使用任何 python 库,如 numpy、pandas 等。仅使用 python 解决
注意 - 只有 3 个类别并且产品 ID 是唯一列,订单 ID 和客户 ID 不重复。
OrderID ProdID Prodcategory Client ID
4997 1 Cat 1 21
4997 2 Cat 1 22
4997 3 Cat 2 23
4997 4 Cat 3 24
2001 5 Cat 1 25
2001 6 Cat 2 26
2001 7 Cat 2 27
2001 8 Cat 2 28
2001 9 Cat 3 29
2376 10 Cat 3 30
2376 11 Cat 1 31
2376 12 Cat 2 32
2376 13 Cat 3 33
2376 14 Cat 1 34
我想要在所有订单中出现次数最多的那对。例如在 Order 4997 (Cat 1, Cat 2) (Cat 2, Cat 3) 和 (Cat 1, Cat 3 ) 中都出现了一次。在 2001 年的订单中,(Cat 1, Cat 2) (Cat1, Cat 3) (Cat 2, Cat 3) 出现一次总计,我想要在所有订单中哪对具有最多的价值计数,即出现最多
我的方法
# Import required libraries
import pandas as pd
import matplotlib.pyplot as plt
# Read the data into the dataframe
#df = pd.read_clipboard()
df
df.columns
df["Product category "].value_counts()
mylabels = ['Cat 2', 'Cat 1', 'Cat 3']
plt.pie(df["Product category "].value_counts(), labels = mylabels)
plt.show()
但此方法仅显示,总值计数而不是重复对
尝试使用 pivot_table 来计算出现次数。 Cat 1 和 Cat 2 似乎卖得最多。
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
data="""
OrderID,ProdID,Prodcategory,ClientID
4997,1,'Cat 1',21
4997,2,'Cat 1',22
4997,3,'Cat 2',23
4997,4,'Cat 3',24
2001,5,'Cat 1',25
2001,6,'Cat 2',26
2001,7,'Cat 2',27
2001,8,'Cat 2',28
2001,9,'Cat 3',29
2376,10,'Cat 3',30
2376,11,'Cat 1',31
2376,12,'Cat 2',32
2376,13,'Cat 3',33
2376,14,'Cat 1',34
"""
# a. create a dataframe from data
df = pd.read_csv(StringIO(data), sep=',')
# b. count the occurrence of Productcategory using a pivot_table
category_list=df['Prodcategory'].unique()
order_list=df['OrderID'].unique()
dict=defaultdict(tuple)
combinations_object = itertools.combinations(category_list, 2)
for item in combinations_object:
for order in order_list:
filter="OrderID=={} and (Prodcategory=='{}' or Prodcategory=='{}')".format(order,item[0],item[1])
key=item+(order,)
count=len(df.query(filter))
if count>0:
dict[key]=count
for item,value in dict.items():
print(item,value)
输出:
key:(category combinations and orderID)
key occurrences
('Cat 1', 'Cat 2', 4997) 3
('Cat 1', 'Cat 2', 2001) 4
('Cat 1', 'Cat 2', 2376) 3
('Cat 1', 'Cat 3', 4997) 3
('Cat 1', 'Cat 3', 2001) 2
('Cat 1', 'Cat 3', 2376) 4
('Cat 2', 'Cat 3', 4997) 2
('Cat 2', 'Cat 3', 2001) 4
('Cat 2', 'Cat 3', 2376) 3
您可以将列聚合为 lit,将 itertools 中的组合应用于列表集(以删除重复项),然后将结果扩展到新列以调用 value_counts
from itertools import combinations
cats=df.groupby('OrderID')['Prodcategory']\
.agg(list)\
.apply(lambda x:list(combinations(set(x),2)))\
.explode()
cats
OrderID
2001 (Cat2, Cat1)
2001 (Cat2, Cat3)
2001 (Cat1, Cat3)
2376 (Cat2, Cat1)
2376 (Cat2, Cat3)
2376 (Cat1, Cat3)
4997 (Cat2, Cat1)
4997 (Cat2, Cat3)
4997 (Cat1, Cat3)
cats.value_counts()
(Cat2, Cat3) 3
(Cat1, Cat3) 3
(Cat2, Cat1) 3
使用crosstab/groupby().size()
获取订单中每个类别的出现次数。然后矩阵乘法计算共现:
ct = pd.crosstab(df['OrderID'], df['Prodcategory']).gt(0).astype(int)
co_occur = (ct.T @ ct)
输出:
Prodcategory Cat 1 Cat 2 Cat 3
Prodcategory
Cat 1 3 3 3
Cat 2 3 3 3
Cat 3 3 3 3
然后您可以屏蔽重复项,堆叠并使用输出:
counts = co_occur.where(np.tri(len(co_occur), k=-1, dtype=bool)).stack()
即:
Prodcategory Prodcategory
Cat 2 Cat 1 3.0
Cat 3 Cat 1 3.0
Cat 2 3.0
dtype: float64
和counts.idxmax()
会给你出现次数最多的一对。
鉴于下面的 table 是数据集,给出了数据集的 4 列和前 14 行,但有超过 10,000 行。在一个订单中有多个产品被卖给客户。
我想知道,在所有订单中,哪对产品类别出现的次数最多?示例(Cat1 和 Cat2)
使用任何 python 库,如 numpy、pandas 等。仅使用 python 解决
注意 - 只有 3 个类别并且产品 ID 是唯一列,订单 ID 和客户 ID 不重复。
OrderID ProdID Prodcategory Client ID
4997 1 Cat 1 21
4997 2 Cat 1 22
4997 3 Cat 2 23
4997 4 Cat 3 24
2001 5 Cat 1 25
2001 6 Cat 2 26
2001 7 Cat 2 27
2001 8 Cat 2 28
2001 9 Cat 3 29
2376 10 Cat 3 30
2376 11 Cat 1 31
2376 12 Cat 2 32
2376 13 Cat 3 33
2376 14 Cat 1 34
我想要在所有订单中出现次数最多的那对。例如在 Order 4997 (Cat 1, Cat 2) (Cat 2, Cat 3) 和 (Cat 1, Cat 3 ) 中都出现了一次。在 2001 年的订单中,(Cat 1, Cat 2) (Cat1, Cat 3) (Cat 2, Cat 3) 出现一次总计,我想要在所有订单中哪对具有最多的价值计数,即出现最多
我的方法
# Import required libraries
import pandas as pd
import matplotlib.pyplot as plt
# Read the data into the dataframe
#df = pd.read_clipboard()
df
df.columns
df["Product category "].value_counts()
mylabels = ['Cat 2', 'Cat 1', 'Cat 3']
plt.pie(df["Product category "].value_counts(), labels = mylabels)
plt.show()
但此方法仅显示,总值计数而不是重复对
尝试使用 pivot_table 来计算出现次数。 Cat 1 和 Cat 2 似乎卖得最多。
import pandas as pd
import matplotlib.pyplot as plt
from io import StringIO
data="""
OrderID,ProdID,Prodcategory,ClientID
4997,1,'Cat 1',21
4997,2,'Cat 1',22
4997,3,'Cat 2',23
4997,4,'Cat 3',24
2001,5,'Cat 1',25
2001,6,'Cat 2',26
2001,7,'Cat 2',27
2001,8,'Cat 2',28
2001,9,'Cat 3',29
2376,10,'Cat 3',30
2376,11,'Cat 1',31
2376,12,'Cat 2',32
2376,13,'Cat 3',33
2376,14,'Cat 1',34
"""
# a. create a dataframe from data
df = pd.read_csv(StringIO(data), sep=',')
# b. count the occurrence of Productcategory using a pivot_table
category_list=df['Prodcategory'].unique()
order_list=df['OrderID'].unique()
dict=defaultdict(tuple)
combinations_object = itertools.combinations(category_list, 2)
for item in combinations_object:
for order in order_list:
filter="OrderID=={} and (Prodcategory=='{}' or Prodcategory=='{}')".format(order,item[0],item[1])
key=item+(order,)
count=len(df.query(filter))
if count>0:
dict[key]=count
for item,value in dict.items():
print(item,value)
输出:
key:(category combinations and orderID)
key occurrences
('Cat 1', 'Cat 2', 4997) 3
('Cat 1', 'Cat 2', 2001) 4
('Cat 1', 'Cat 2', 2376) 3
('Cat 1', 'Cat 3', 4997) 3
('Cat 1', 'Cat 3', 2001) 2
('Cat 1', 'Cat 3', 2376) 4
('Cat 2', 'Cat 3', 4997) 2
('Cat 2', 'Cat 3', 2001) 4
('Cat 2', 'Cat 3', 2376) 3
您可以将列聚合为 lit,将 itertools 中的组合应用于列表集(以删除重复项),然后将结果扩展到新列以调用 value_counts
from itertools import combinations
cats=df.groupby('OrderID')['Prodcategory']\
.agg(list)\
.apply(lambda x:list(combinations(set(x),2)))\
.explode()
cats
OrderID
2001 (Cat2, Cat1)
2001 (Cat2, Cat3)
2001 (Cat1, Cat3)
2376 (Cat2, Cat1)
2376 (Cat2, Cat3)
2376 (Cat1, Cat3)
4997 (Cat2, Cat1)
4997 (Cat2, Cat3)
4997 (Cat1, Cat3)
cats.value_counts()
(Cat2, Cat3) 3
(Cat1, Cat3) 3
(Cat2, Cat1) 3
使用crosstab/groupby().size()
获取订单中每个类别的出现次数。然后矩阵乘法计算共现:
ct = pd.crosstab(df['OrderID'], df['Prodcategory']).gt(0).astype(int)
co_occur = (ct.T @ ct)
输出:
Prodcategory Cat 1 Cat 2 Cat 3
Prodcategory
Cat 1 3 3 3
Cat 2 3 3 3
Cat 3 3 3 3
然后您可以屏蔽重复项,堆叠并使用输出:
counts = co_occur.where(np.tri(len(co_occur), k=-1, dtype=bool)).stack()
即:
Prodcategory Prodcategory
Cat 2 Cat 1 3.0
Cat 3 Cat 1 3.0
Cat 2 3.0
dtype: float64
和counts.idxmax()
会给你出现次数最多的一对。