购物篮分析

Market Basket Analysis

我有以下关于零售店的 pandas 交易数据集:

print(df)

product       Date                   Assistant_name
product_1     2017-01-02 11:45:00    John
product_2     2017-01-02 11:45:00    John
product_3     2017-01-02 11:55:00    Mark
...

我想创建以下数据集,用于购物篮分析:

product       Date                   Assistant_name  Invoice_number
product_1     2017-01-02 11:45:00    John            1
product_2     2017-01-02 11:45:00    John            1
product_3     2017-01-02 11:55:00    Mark            2
    ...

简单地说,如果一笔交易有相同的Assistant_name和日期,我假设它确实生成了一个新的发票。

使用 pandas 类别是一种方法:

df['Invoice'] = list(zip(df['Date'], df['Assistant_name']))
df['Invoice'] = df['Invoice'].astype('category').cat.codes + 1

#               product      Date Assistant_name  Invoice
# product_1  2017-01-02  11:45:00           John        1
# product_2  2017-01-02  11:45:00           John        1
# product_3  2017-01-02  11:55:00           Mark        2

此方法的好处是您可以轻松检索映射字典:

dict(enumerate(df['Invoice'].astype('category').cat.categories, 1))
# {1: ('11:45:00', 'John'), 2: ('11:55:00', 'Mark')}

最简单的是 factorize 将列连接在一起:

df['Invoice'] = pd.factorize(df['Date'].astype(str) + df['Assistant_name'])[0] + 1
print (df)
     product                 Date Assistant_name  Invoice
0  product_1  2017-01-02 11:45:00           John        1
1  product_2  2017-01-02 11:45:00           John        1
2  product_3  2017-01-02 11:55:00           Mark        2

如果性能很重要,请使用 pd.lib.fast_zip:

df['Invoice']=pd.factorize(pd.lib.fast_zip([df.Date.values, df.Assistant_name.values]))[0]+1

时间:

#[30000 rows x 3 columns]
df = pd.concat([df] * 10000, ignore_index=True)

In [178]: %%timeit
     ...: df['Invoice'] = list(zip(df['Date'], df['Assistant_name']))
     ...: df['Invoice'] = df['Invoice'].astype('category').cat.codes + 1
     ...: 
9.16 ms ± 54.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [179]: %%timeit
     ...: df['Invoice'] = pd.factorize(df['Date'].astype(str) + df['Assistant_name'])[0] + 1
     ...: 
11.2 ms ± 395 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [180]: %%timeit 
     ...: df['Invoice'] = pd.factorize(pd.lib.fast_zip([df.Date.values, df.Assistant_name.values]))[0] + 1
     ...: 
6.27 ms ± 93.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)