使用 numpy .max/ numpy.min 作为时间戳值



我有一个销售表,其中包含客户、交易日期列等。我在 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 方法计算日期之间的最小值和最大值。 还是我应该使用其他与日期时间相关的方法?

您应该使用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

最新更新