我有数据框
ID date
111 11-11-2016
111 14-11-2016
111 17-11-2016
222 24-11-2016
222 27-11-2016
我需要计算每个ID的数据之间的差异。 我用的是
df['duration'] = df.groupby(['ID','date']).date.apply(lambda x: x - x.iloc[0])
idx = df.groupby(['ID'])['duration'].transform(max) == df['count date']
但它返回错误的结果。 我怎样才能得到理想的呢? 我需要得到
ID count date
111 6
222 3
最佳答案
>>> df.groupby('ID')['date'].apply(lambda x: x.max() - x.min())
ID
111 6 days
222 3 days
也可以使用numpy.ptp
>>> df.groupby('ID')['date'].agg(np.ptp)
ID
111 6 days
222 3 days
关于python - Pandas:计算日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41613313/