【问题标题】:Finding Unique values in a Dataset在数据集中查找唯一值
【发布时间】:2013-11-27 14:20:57
【问题描述】:

我有一个数据集如下:

Visitor ID    Page Id      TimeStamp
1             a            x1
2             b            x2
3             c            x3 
2             d            x4

以下是数据的规则:

1)。将其视为访问者访问网站并进行一些交互的 Web 数据。 VID 代表访客唯一 ID。 Page Id 是他访问过的页面的 ID,Time stamp 是访问的时间。

2)。如果页面刷新,则时间戳将更改,因此将在数据集中创建一个新行,其 VID、页面 ID 的值相同,但时间戳的值不同。

3)。如果访问者点击其他页面,时间戳和页面 ID 都会更改。假设他首先在页面“a”上,然后转到页面“b”,因此他将在数据集中有另一条具有相同 VID 的记录,但页面 id 现在 =b 并且时间戳是新的时间戳。

问题:

我想找出在访问页面“a”之后访问页面“b”的所有唯一 VID。请注意,我希望它用于特定的会话或一天。

有人可以帮助使用 sql 和 Pythonic 的方式吗?

谢谢

【问题讨论】:

    标签: python sql


    【解决方案1】:

    只是为了让你(或其他人)开始 Pythonic 部分:

    如果可以,请将您的数据放入 NumPy record array(例如使用 numpy.genfromtxt):

    records = np.array([(1,'a',100),
                        (2,'a',100),
                        (1,'b',200),
                        (1,'a',300)],
                       dtype=dict(names=['vid','pid','time'],
                                  formats=['i4','S1','i4']))
    

    “时间”字段是一些可比较的 int/float/str 或 python datetime.datetime 实例。实际上'x1','x2' 等也可以。然后你可以做类似的事情

    records_of_interest = records[records['time'] > 200]
    

    然后我会遍历访问者 ID 并查看他们的记录是否符合您的条件:

    target_vids = []
    vids = np.unique(records['vid'])
    for vid in vids:
        # get the indices for the visitor's records
        ii = np.where(records['vid'] == vid)[0]
        # make sure they visited page 'b' at all
        if 'b' not in records[ii]['pid']:
            continue
        # check whether they visited 'a' before 'b' 
        lastvisit_b = np.where(records[ii]['pid'] == 'b')[0].max()
        firstvisit_a = np.where(records[ii]['pid'] == 'a')[0].min()
        if firstvisit_a < lastvisit_b:
            target_vids.append(vid)
    

    target_vids 现在包含您想要的访客 ID。

    再说一次,SQL 也有 Python 接口,这可能会将您的问题减少到一种语言...

    【讨论】:

      【解决方案2】:

      sql 方式是:

      select distinct(t1.vid) from my_table as t1 
      inner join my_table as t2 on t1.vid = t2.vid
      where t1.page_id = 'a' and t2.page_id='b' and t1.time < t2.time;
      

      【讨论】:

        【解决方案3】:
        select unique(visitor_id) from table_name where page_id="a" and visitor_id in (select unique(visitor_id) from table_name where page_id="b" and timestamp="any day");
        

        【讨论】:

        • 我不认为这符合预期。这将选择分页为 a 和 b 的所有 VID。我需要的是访问页面a后访问页面b的VID。
        猜你喜欢
        • 2014-09-07
        • 2012-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-09
        • 1970-01-01
        • 2017-05-07
        • 2022-08-19
        相关资源
        最近更新 更多