计算数据帧中分类成对组合的数量



我正试图计算数据集中分类特征之间存在的唯一交互的总数。

假设一个小数据帧:

Fruit          Vegetable       Animal
---------------------------------------------------
0          Apple          Carrot          Rabbit
1          Apple          Lemon           Fish
2          Banana         Cucumber        Cat
3          Orange         Lemon           Fish
4          Melon          Lettuce         Cat
5          Mango          Lemon           Fish
---------------------------------------------------

如何计算特征之间唯一的成对交互的总数?水果栏有5只独特的猫,蔬菜栏有4只独特的猫咪,动物栏有3只独特的小猫。因此,如果我没有弄错的话,所有三列的所有可能组合的总和是5 x 4 x 3=60。然而,我想计算给定数据集中存在的可能成对组合的数量。

例如,Apple-Carrot是一个,Carrot-Rabbit是另一个。Lemon-Fish也算作1,尽管在数据集中出现了三次。

您可以首先查找类别的所有可能组合,然后查找类别内uniques元素的所有可能的组合:

# find unique elements per column
unique_elements_per_column={i:df[i].unique() for i in df.columns}
# create possible category combinations
category_pairs=list(itertools.combinations(df.columns,2))
# find all possible combinations by category pair
all_possible_combinations=[list(itertools.product(unique_elements_per_column[i[0]],unique_elements_per_column[i[1]])) for i in category_pairs]
# sum of all possible combinations by category pair
sum_combinations=[len(i) for i in all_possible_combinations]
df_out=pd.DataFrame(columns=['all_possible_combinations'],index=category_pairs,data=sum_combinations)

#output:
all_possible_combinations
(Fruit, Vegetable)                          20
(Fruit, Animal)                             15
(Vegetable, Animal)                         12

这是我自己解决问题的方法。不过,可能还有另一种方法可以达到同样的结果:


import pandas as pd
df = pd.DataFrame({"Fruit": ["Apple", "Apple", "Banana", "Orange", "Melon", "Mango"],
"Vegetable": ["Carrot", "Lemon", "Cucumber", "Lemon", "Lettuce", "Lemon"],
"Animal": ["Rabbit", "Fish", "Cat", "Fish", "Cat", "Fish"]})
columns = ["Fruit", "Vegetable", "Animal"]
unq_sum = 0
consumed = []
for col in columns:
consumed.append(col)
others = [x for x in columns if x not in consumed]
for inner_col in others:
unq_sum += df.groupby(col)[inner_col].nunique().sum()
print(unq_sum)
>>> 16

@Gabriele的答案是找到可能的唯一配对组合的总数。在该数据集中,现有条目对应于所有可能的成对唯一组合的16/47 = 34.04%

最新更新