Py学习  »  Python

在数据帧中找到最常见的组合——Python

GeoP • 4 年前 • 1630 次点击  

我正在使用pandas,我试图找到一种方法,可以在我的数据文件中获得人们使用的最常见的产品组合。

假设接下来三个AA、BB和CC的每一列代表一个完全不同的产品,0表示我不使用这个产品,1表示我使用它。此外,每一行代表一个完全不同的买家。

例如,在我的示例中,最常见的组合是AA和CC产品,因为我有三个人使用它们,如第1、4、5行所示。

我的结果是“最常见的组合是三个人使用的AA和CC产品”。

我希望这次我能更好地向你解释

下面是我的数据帧示例:

AA  | BB  | CC
_______________
1   | 0   |  1
0   | 0   |  1
0   | 1   |  0
1   | 0   |  1
1   | 0   |  1
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129996
文章 [ 2 ]  |  最新文章 4 年前
GeoP
Reply   •   1 楼
GeoP    4 年前

在你回答之前,我几乎能想出我问题的答案,但你 wjandrea 部分正确,谢谢。

首先,我必须一行一行地浏览整个数据帧,每次这样寻找一个值,然后得到我的产品名1。

combination = df.apply(lambda row: row[row == 1].index.tolist(), axis=1)
combination = pd.DataFrame(combination)

在那之后,我创建了一个新专栏,列有每个用户使用的产品的名称,我必须将它们分开。

df['Products'] = [' , '.join(map(str, l)) for l in combination[0]]

然后我就用了你的代码,我得到了我想要的

wjandrea
Reply   •   2 楼
wjandrea    4 年前

一旦你 count duplicate rows ,只需要做一些工作就可以得到相应的标签。

以下是我将如何做到这一点,尽管我对熊猫不太熟悉,所以可能有更好的方法。首先,df应该是布尔值。

import pandas as pd

df = pd.DataFrame({
    'AA': [1, 0, 0, 1, 1],
    'BB': [0, 0, 1, 0, 0],
    'CC': [1, 1, 0, 1, 1]}
    ).astype(bool)

# Count duplicate rows
counts = df.groupby(df.columns.tolist()).size()
# Get most common rows
maxima = counts[counts==counts.max()]
for combination, count in maxima.iteritems():
    # Select matching labels
    labels = df.columns[list(combination)]
    print(*labels, count)

输出:

AA CC 3

部分结果:

>>> counts
AA     BB     CC   
False  False  True     1
       True   False    1
True   False  True     3
dtype: int64

>>> maxima
AA    BB     CC  
True  False  True    3
dtype: int64