使用 Python 在一天内分发随机数据记录

Distributing the random data records across the day using Python

我正在设计数据模拟器,它根据限制生成一些记录,限制可以是 100 到 10000 之间的任何值

limit = 100

记录应全天分发 例如:第 0 小时 15% 的记录,第 1 小时 20%,第 2 小时 5% 等等...

如何使用python模拟这种分布,哪个库可以帮助设计逻辑?

现在我可以模拟如下记录

t_id    t_amount    gateway    transaction_date
101     30          Master     11/05/2016
102     10          Amex       11/05/2016

如果您查看交易日期,它没有时间戳。但是我想有如下记录的时间戳,其中所有100条记录都分布在一整天,如何实现?

t_id    t_amount    gateway    transaction_date
101     30          Master     11/05/2016 00:21:42
102     10          Amex       11/05/2016 01:22:42

我看一下 random 包的文档,它是标准库的一部分,您会发现它确实支持生成具有正态(高斯)分布的数字。

这是一种按照您描述的方式生成内容的方法。请注意,limit 可以随机设置,每小时的重量也可以。

In [78]: df.tail()
Out[78]:
                    gateway  t_amount  t_id
transaction_date
2016-11-05 03:00:00    Amex        68   195
2016-11-05 03:00:00    Amex        41   196
2016-11-05 03:00:00  Master        66   197
2016-11-05 03:00:00    Amex        59   198
2016-11-05 03:00:00    Amex        45   199

下面的代码根据所需的观察次数 limit 和每小时的重量预先生成小时数。然后它使用 Numpy 的随机模块生成样本数据。查看他们的 documentation 以了解其他发行版。

import numpy as np
import pandas as pd

#total number of observations:
limit = 10**2
N = 100
#percent of transactions during that hour.
weights_per_hour= (np.array([.35, .25, .25, .15])*limit).astype(int)

#generate time range using Pandas datetime functions
time_range = pd.date_range(start = '20161105',freq='H', periods=4)

#generate data index according to the hour distribution.
time_indx  = time_range.repeat(weights_per_hour)

#create temp data frame as a housing unit.
dat_dict =  {"t_id":[x+100 for x in range(N)], "transaction_date":time_indx}
temp_df = pd.DataFrame(dat_dict)

#enter the choices for transaction type
gateway_choice = np.array(['Master', 'Amex'])

#generate random data
rnd_df = pd.DataFrame({"t_amount":np.random.randint(low=1, high=100,size=limit), "gateway":np.random.choice(gateway_choice,limit)})

#attach random data to to temp_df
df = pd.concat([rnd_df, temp_df], axis=1)
df.set_index('transaction_date', inplace=True)

在上面的代码中,索引是时间戳格式。您可能需要尝试才能打印它,但它确实已存储。要将其转换为 Pandas 非索引格式,请使用 pd.index.to_datetime()df.reset_index(df.index) 将其放入数据框。