【问题标题】:Create a vector of dates in python pandas在 python pandas 中创建一个日期向量
【发布时间】:2020-09-24 02:14:00
【问题描述】:

我的数据中有三列:

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

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

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

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

我能够将 numpy 函数应用于单个向量,但无法在我的数据框中创建向量,然后将它们应用于列中的每个值。我尝试了几种方法来做到这一点,但由于我是 pandas 的新手,所以我无法弄清楚。

有人可以提供一些方向吗?我将不胜感激。

【问题讨论】:

    标签: python python-3.x pandas numpy


    【解决方案1】:

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

    使用的模块:

    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
    

    【讨论】:

      【解决方案2】:

      试试:

      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, ...
      

      【讨论】:

        猜你喜欢
        • 2016-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-13
        • 2013-01-05
        • 2019-07-26
        相关资源
        最近更新 更多