【问题标题】:pandas: groupby and calculate time difference from first element in each grouppandas:groupby并计算每组中第一个元素的时间差
【发布时间】:2017-07-20 06:46:12
【问题描述】:

在熊猫中,我想按列中的值对数据进行分组,然后计算每个时间戳与该组中第一个时间戳之间的时间差。

例如,考虑以下 DataFrame:

# Create data. 
d = {'foo': ['001', '001', '002', '002', '002'], 
     'timestamp': ['2015-02-24 19:12:00', '2015-02-24 21:38:00', '2015-02-25 03:41:00', '2015-02-25 03:44:00', '2015-02-25 03:49:00']}
df = pd.DataFrame(d, columns = ['foo', 'timestamp'])
df['timestamp'] = pd.DatetimeIndex(pd.to_datetime(df['timestamp'])).tz_localize('UTC')
>>> print df
   foo                 timestamp
0  001 2015-02-24 19:12:00+00:00
1  001 2015-02-24 21:38:00+00:00
2  002 2015-02-25 03:41:00+00:00
3  002 2015-02-25 03:44:00+00:00
4  002 2015-02-25 03:49:00+00:00

期望的输出是:

   foo                 timestamp    output
0  001 2015-02-24 19:12:00+00:00       NaT
1  001 2015-02-24 21:38:00+00:00  02:26:00
2  002 2015-02-25 03:41:00+00:00       NaT
3  002 2015-02-25 03:44:00+00:00  00:03:00
4  002 2015-02-25 03:49:00+00:00  00:08:00

.diff() 的使用得到以下结果,但不是预期的结果。

>>> d.groupby('foo')['timestamp'].diff()
0        NaT
1   02:26:00
2        NaT
3   00:03:00
4   00:05:00

【问题讨论】:

    标签: python pandas time-series


    【解决方案1】:

    使用assign + apply

    df.assign(output=df.groupby('foo').timestamp.apply(lambda x: x - x.iloc[0]))
    
       foo                 timestamp   output
    0  001 2015-02-24 19:12:00+00:00 00:00:00
    1  001 2015-02-24 21:38:00+00:00 02:26:00
    2  002 2015-02-25 03:41:00+00:00 00:00:00
    3  002 2015-02-25 03:44:00+00:00 00:03:00
    4  002 2015-02-25 03:49:00+00:00 00:08:00
    

    【讨论】:

    • 谢谢!理想情况下,我希望每个组中output 的第一个元素是NaN(或NaT)而不是00:00:00。如果您也可以展示如何执行此操作,我会将答案标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 2018-08-26
    • 2021-11-19
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多