分析数据集的加法和减法

数据挖掘 Python sql 擅长
2022-02-20 22:21:32

我有以下形式的数据集:

Product    |    Date
123        |    2019-01-01
456        |    2019-01-01
123        |    2019-01-02
123        |    2019-01-03
456        |    2019-01-03
123        |    2019-01-04
456        |    2019-01-04
789        |    2019-01-04

这只是一个简化版本。全套有约 300 种产品和四个月的数据。我想了解产品集如何随时间变化。显然很容易计算每天的数量,看到我在 1 月 2 日失去了一件产品,在 1 月 4 日获得了一件,但后来我不知道那是什么产品。

有没有更系统的方法来解决这个问题?理想情况下,输出将向我显示日期列表以及当天退出/添加的产品。我之前考虑过 min(date), max(date) 副产品,但是产品可以重复删除和添加,我不会以这种方式来回捕捉。

可用的环境是 Python、SQL 和 Excel。

1个回答

此响应基于您的域。例如销售,一个产品可能不是每天都售出,因此不会有记录。

根据您希望每天在数据集中看到产品出现的数据集,您可以考虑以下方法。

数学上:

A = the set of all possibilities (i.e. product occurrence for each date - you could generate this and use ) 

B = sample data set provided would be provided

C = A - B
  = days that a product was missing. 

DPART1 = You could then continue by retrieving the min(date) and max(date) for each product in the dataset to represent the introduction of the new product and possible cease of an existing product. 

D= You could then filter the dataset (C) to remove dates less than the min(date) and greater than the maxdate).

In terms of sql:
A - Cartesion/Cross product of all your products and dates
B = Your current sample data set
C = SELECT * FROM A MINUS SELECT * FROM B 
DPART1 = SELECT PRODUCT, MIN(date) as INTRODUCED_DATE, MAX(date) as CEASED_DATE from YourSampleDataSET GROUP BY PRODUCT
D = SELECT C.PRODUCT, C.Date FROM C LEFT JOIN DPART1 ON C.PRODUCT = DPART1.PRODUCT
    WHERE DPART1.PRODUCT IS NULL OR (
       C.Date BETWEEN DPART1.INTRODUCED_DATE AND DPART1.CEASED_DATE
    ) 

NB。DPART1.PRODUCT IS NULL确保您不会过滤可能不在样本子集中的产品。

操作方面的考虑,我会推荐您的数据库中的索引来协助查询,并在可能的情况下进行分区。