在python panda中创建日期向量



我的数据中有三列:

mall_id product_id sold_date
13       10001     04-01-2020
13       10002     05-06-2020
14       10001     03-01-2020
13       10001     05-02-2020

我想从sold_date为mall_id、product_id的每个唯一组合创建一个向量。向量的长度应为max(sold_date(-min(sold_date(,并且应为1和0的形式(例如[0,1,0,0,0,1,11](,使得每个数字表示当天是否为mall_id product_id组合进行了购买。(即0表示当天没有购买,1表示进行了购买(。

创建向量后,我想用以下numpy函数将其转换为pandas中的一个新列:

times_1 = np.diff(np.where(vector))
np.std(times_1)/np.mean(times_1)

我可以将numpy函数应用于单个向量,但无法在数据帧中创建向量,然后将它们应用于列中的每个值。我尝试了几种方法,但都没能解决,因为我是熊猫的新手。

有人能提供一些指导吗?我真的很感激。

我的熊猫技能有点生疏,所以我的尝试可能不太理想。

使用的模块:

import datetime as dt
import numpy as np
import pandas as pd

设置DataFrame(您已经有了它(:

columns = ['mall_id', 'product_id', 'sold_date']
data = [[13, 10001, '04-01-2020'],
[13, 10002, '05-06-2020'],
[14, 10001, '03-01-2020'],
[14, 10001, '05-02-2020'],
[13, 10001, '05-02-2020']]
df = pd.DataFrame(data, columns=columns)

将列sold_date转换为正确的日期(我不知道日期的第一部分或第二部分是否代表月/日,所以这可能是错误的(:

df['sold_date'] = [dt.date(int(date[6:]), int(date[3:5]), int(date[:2]))
for date in df['sold_date'].values]

设置一个覆盖天数范围的数组(这是全局性的,即不是针对每个mall_id和product_id组合(:

start, end = df['sold_date'].min(), df['sold_date'].max()
days = np.array([start + dt.timedelta(days=i)
for i in range((end - start).days + 1)])

将索引从mall_id和product_id:列更改为多索引

df.set_index(['mall_id', 'product_id'], drop=True, inplace=True)
df.sort_index(inplace=True)

循环mall_id和product_id组合,创建相应的向量,并将其存储在字典中:

# Initialising dictionary for results
sales = {m_id: {} for m_id, _ in df.index}
# Loop over index
for m_id, p_id in df.index:
# Determining on which days sales happened
sale_days = np.array([(1 if day in df.loc[(m_id, p_id)].values else 0)
for day in days])
# Storing result in dictionary
sales[m_id][p_id] = sale_days

尝试:

def trans_dt(x):
m, M = x.min(), x.max()
r = [1 if x.eq(m+pd.to_timedelta(d, unit="D")).any() else 0 for d in range((M-m).days+1)]
return r
# only if not done already:
df["sold_date"] = pd.to_datetime(df["sold_date"], format="%d-%m-%Y")
res = df.groupby(["mall_id", "product_id"], as_index=False)["sold_date"].agg(trans_dt)

输出:

>>> res
mall_id  ...                                          sold_date
0       13  ...  [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
1       13  ...                                                [1]
2       14  ...  [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...

最新更新