Skip to main content
 首页 » 编程设计

python之根据条件获取同一 pandas 数据框中同一列的两个值之间的差异

2025年04月02日13zhwl

我有一个格式为 df1 的 Pandas 数据帧:

df1.head() 
 
  action id     ts 
0   A   3   2016-01-28 06:14:08.249000 
1   B   3   2016-01-28 07:08:49.901000 
2   A   4   2016-01-28 10:42:27.228000 
3   B   4   2016-01-29 04:15:33.724000 
4   B   4   2016-01-29 04:20:33.724000 
5   A   5   2016-01-28 11:12:51.892000 

列的数据类型: (action: string, id: int,ts: Series(用 pandas.to_datetime() 把它从字符串转换过来))

我想要的是,同一数据帧中的一个新列/另一个系列在相同 ID 的 Action “A”和 Action “B”之间具有时间差。唯一的事情是,我需要第一次出现操作 'A',如 min(ts) 中的每个 id,然后是减去的值,因为操作 'B' 必须在操作 'B' I 之后发生需要确定第一次出现 Action “A”和 Action “B”之间的延迟

我能够使用 groupby()、merge() 和 unstack() 获取它,但我无法获取 min(ts) 在此。

提前致谢。

请您参考如下方法:

实现这一目标的一种方法是这样的:

In [87]: df 
Out[87]: 
  action  id                      ts 
0      B   3 2016-01-28 06:14:08.249 
1      A   3 2016-01-28 07:08:49.901 
2      A   4 2016-01-28 10:42:27.228 
3      B   4 2016-01-29 04:15:33.724 
4      B   4 2016-01-29 04:20:33.724 
5      B   5 2016-01-28 11:12:51.892 
 
In [88]: grp = df.groupby(['id']) 
 
In [89]: grp.apply(lambda x: x[x['action'] == 'B'].ts.max()) - \ 
   ....: grp.apply(lambda x: x[x['action'] == 'A'].ts.min()) 
Out[89]: 
id 
3   -1 days +23:05:18.348000 
4            17:38:06.496000 
5                        NaT 
dtype: timedelta64[ns] 

注意:请注意您的示例数据集 - id 3 的操作 B 发生在操作 A

之前

如果你想消除NaT,你可以使用.dropna():

In [82]: result = (grp.apply(lambda x: x[x['action'] == 'B'].ts.max()) - \ 
   ....:           grp.apply(lambda x: x[x['action'] == 'A'].ts.min())).dropna() 
 
In [83]: result 
Out[83]: 
id 
3   -1 days +23:05:18.348000 
4            17:38:06.496000 
dtype: timedelta64[ns]