市场篮子分析

时间:2018-02-18 12:44:21

标签: python python-3.x pandas 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和日期,我认为它确实会生成新的发票。

2 个答案:

答案 0 :(得分:4)

最简单的是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)

答案 1 :(得分:1)

使用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')}