【问题标题】:Using numpy.max/ numpy.min for timestamp values使用 numpy.max/ numpy.min 作为时间戳值
【发布时间】:2018-12-12 23:26:03
【问题描述】:

我有一个包含 custid、交易日期列等的销售表。我在 custid 列上使用 groupby,然后使用 agg 方法获取最大日期(获取该特定客户的最新交易日期)和最小日期(获取他在商店交易的第一个日期)。

我的代码如下:

sales['transdate'] = pd.to_datetime(sales['transdate']) # Converting the transdate column from string to timestamps.
sales['custid'].groupby.transdate({'count': np.count_nonzero ,'first': np.min, 'last' : np.max})

我想知道是否可以

使用 np.min/max 方法计算日期之间的最小值和最大值。 还是我应该使用其他一些与日期时间相关的方法?

【问题讨论】:

    标签: python pandas numpy time-series pandas-groupby


    【解决方案1】:

    您应该使用groupby.agg 来应用多个聚合函数。

    另请注意,使用 Pandas 可以通过字符串调用许多聚合函数。在这种情况下,您可以使用'size''min''max'。建议使用字符串,因为字符串表示由 Pandas 映射到经过测试的高效算法。

    这是一个演示:

    df = pd.DataFrame([['2017-01-14', 1], ['2017-12-05', 2], ['2017-06-15', 2],
                       ['2017-03-21', 1], ['2017-04-25', 2], ['2017-02-12', 1]],
                      columns=['transdate', 'custid'])
    
    df['transdate'] = pd.to_datetime(df['transdate'])
    
    agg_dict = {'count': 'size', 'first': 'min', 'last': 'max'}
    
    res = df.groupby('custid')['transdate'].agg(agg_dict)
    
    print(res)
    
            count      first       last
    custid                             
    1           3 2017-01-14 2017-03-21
    2           3 2017-04-25 2017-12-05
    

    【讨论】:

    • 我认为使用 numpy 方法效率更高。而且,使用 numpy 或 string 方法之间的权衡是什么。
    • @aspiring1,通常,字符串指向 NumPy 方法。我之所以偏爱字符串,是因为您知道它们已经过测试。例如,我们使用df.groupby('a')['b'].mean() 信任Pandas 方法(我从未见过有人为此明确指定np.mean),因此没有理由不信任使用"mean" 作为参数的Pandas。一个非 NumPy 性能示例是 len"size",字符串通常更快。
    • 我总是对 df.groupby('a')['b'].mean() 和使用上面的 numpy.mean 是否具有相同的速度感到困惑。
    • @aspiring1,复杂性应该相同。使用 Pandas 方法可能会产生固定的 O(1) 成本,但这应该可以忽略不计。如果这种优化真的很重要,你应该考虑在纯 NumPy 中工作。如果您从数据框中提取 NumPy 数组,则可以优化大多数 Pandas 操作。
    猜你喜欢
    • 2017-11-17
    • 2011-11-21
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    相关资源
    最近更新 更多