我有以下数据:
我想要创建一个新的列,它计算一个IP交换域的次数。
输入:
domain ip timestamp next_domain next_next_domain
0 Google 101 2020-04-01 23:01:41 Facebook N/A
1 Google 101 2020-04-01 23:01:59 Facebook N/A
2 Google 101 2020-04-02 12:01:41 Facebook N/A
3 Facebook 101 2020-04-02 13:11:33 N/A N/A
4 Facebook 101 2020-04-02 13:11:35 N/A N/A
5 Youtube 103 2020-04-21 13:01:41 Google Facebook
6 Youtube 103 2020-04-21 13:11:46 Google Facebook
7 Youtube 103 2020-04-22 01:01:01 Google Facebook
8 Google 103 2020-04-22 02:11:23 Facebook Youtube
9 Facebook 103 2020-04-23 14:11:13 Youtube N/A
10 Youtube 103 2020-04-23 14:11:55 N/A N/A输出:
domain ip timestamp next_domain next_next_domain switch_count
0 Google 101 2020-04-01 23:01:41 Facebook N/A 1
1 Google 101 2020-04-01 23:01:59 Facebook N/A 1
2 Google 101 2020-04-02 12:01:41 Facebook N/A 1
3 Facebook 101 2020-04-02 13:11:33 N/A N/A 1
4 Facebook 101 2020-04-02 13:11:35 N/A N/A 1
5 Youtube 103 2020-04-21 13:01:41 Google Facebook 3
6 Youtube 103 2020-04-21 13:11:46 Google Facebook 3
7 Youtube 103 2020-04-22 01:01:01 Google Facebook 3
8 Google 103 2020-04-22 02:11:23 Facebook Youtube 3
9 Facebook 103 2020-04-23 14:11:13 Youtube N/A 3
10 Youtube 103 2020-04-23 14:11:55 N/A N/A 3IP 101切换1次,因为它来自Google -> Facebook。IP 103切换3次,因为它来自Youtube -> Google -> Facebook -> Youtube。
我怎样才能在熊猫身上做到这一点?
发布于 2022-01-25 19:39:07
您可以对groupby "ip“进行转换,并在转换时检查连续域名是否不同(请注意,我们只是减去1,因为我们也计算了第一个域名,这不包括”开关“):
df['switch'] = df.groupby('ip')['domain'].transform(lambda x: x.shift().ne(x).sum()-1)输出:
domain ip timestamp next_domain next_next_domain switch
0 Google 101 2020-04-01 23:01:41 Facebook NaN 1
1 Google 101 2020-04-01 23:01:59 Facebook NaN 1
2 Google 101 2020-04-02 12:01:41 Facebook NaN 1
3 Facebook 101 2020-04-02 13:11:33 NaN NaN 1
4 Facebook 101 2020-04-02 13:11:35 NaN NaN 1
5 Youtube 103 2020-04-21 13:01:41 Google Facebook 3
6 Youtube 103 2020-04-21 13:11:46 Google Facebook 3
7 Youtube 103 2020-04-22 01:01:01 Google Facebook 3
8 Google 103 2020-04-22 02:11:23 Facebook Youtube 3
9 Facebook 103 2020-04-23 14:11:13 Youtube NaN 3
10 Youtube 103 2020-04-23 14:11:55 NaN NaN 3https://stackoverflow.com/questions/70854516
复制相似问题