使用numpy.max/最小值对于时间戳值

2024-09-28 19:10:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含custid、transaction date列等的sales表。我在custid列上使用groupby,然后使用agg方法来获取max date(获取特定客户的最新交易日期)和min date(获取他在商店的第一个交易日期)。在

我的代码如下:

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})

我想知道是否可以

calculate min and max between dates by using np.min/max methods. or should I be using some other datetime related methods?


Tags: todatetimedatecountnp交易minmax
1条回答
网友
1楼 · 发布于 2024-09-28 19:10:16

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

还请注意,对于Pandas,可以通过字符串调用许多聚合函数。在这种情况下,可以使用'size''min'和{}。建议使用字符串,因为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

相关问题 更多 >