Pandas滑动窗口,揪出刷单黄牛党!
点击上方蓝色字体,关注程序员zhenguo
你好,我是 zhenguo
今天这篇文章是一个关于好玩实用的小案例,使用Pandas的滑动窗口方法确定是否存在刷单行为,给予黄牛党致命一击。
滑动窗口可能是你应用没那么多的方法,但是在处理事件序列的场景中,滑动窗口的价值凸显!
批量随机生成时间戳
实现方法
如下批量生成时间戳,
random_timestamp
函数中,hour
传入小时(24小时制)ymd
表示年月日,默认为2021-12-01
import random
import pandas as pd
defrandom_timestamp(hour, ymd='2021-12-01'):
"""
生成年月日固定,分秒随机的时间戳
:param ymd:
:param hour: 传入小时
:return:
"""
deftstr():
tms = set([random.randrange(1, 59, 2) for _ in range(20)])
return [f'2020-12-01 {hour}:{ms}:{ms}'for ms in tms]
return [pd.Timestamp(ws) for ws in tstr()]
调用
series = random_timestamp(9)
结果:
[Timestamp('2020-12-01 09:01:01'), Timestamp('2020-12-01 09:35:35'), Timestamp('2020-12-01 09:05:05'), Timestamp('2020-12-01 09:07:07'), Timestamp('2020-12-01 09:09:09'), Timestamp('2020-12-01 09:11:11'), Timestamp('2020-12-01 09:13:13'), Timestamp('2020-12-01 09:19:19'), Timestamp('2020-12-01 09:53:53'), Timestamp('2020-12-01 09:55:55'), Timestamp('2020-12-01 09:23:23'), Timestamp('2020-12-01 09:21:21'), Timestamp('2020-12-01 09:29:29'), Timestamp('2020-12-01 09:31:31')]
使用滑动窗口找出频繁刷单用户
需求
定义在20分钟连续下单为:刷单
给你一批交易数据,类型为
pd.Series
,确定这批数据是否存在频繁刷单的行为。使用滑动窗口
Pandas的
rolling
方法,求出固定滑动窗口长度的序列。import pandas as pd
defis_outlier(time_series: pd.Series, outlier_duration=20, outlier_count=5):
"""
outlier_duration分钟内连续交易outlier_count次认为是异常
:param time_series:
:param outlier_duration:
:param outlier_count:
:return:
"""
# 排序
time_series2 = time_series.sort_values()
# 基于最早时间的时间跨度
time_delta = (time_series2 - time_series2.iloc[0]) / np.timedelta64(1, 's') / 60.
# 求得长度为outlier_count的滑动窗口的时间跨度
time_cumsum = time_delta.rolling(outlier_count).sum()
# 若outlier_count次交易的时间小于outlier_duration,就是所定义的刷单,返回True
if (time_cumsum <= outlier_duration).any():
returnTrue
# 不存在刷单
returnFalse
调用
使用小技巧25,生成随机时间戳序列,调用
series = random_timestamp(9) # hour 等于9点
print(series)
result = is_outlier(pd.Series(series))
print(result)
zhenguo原创精华PDF,倾情奉献给你,后台回复对应关键词下载,给文章点个赞:
阅读原文 关键词
数据
方法
小时
时间
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。