将函数应用于pandas中分组数据的单个列

时间:2014-07-03 22:12:41

标签: python pandas dataframe

Theres a pandas dataframe如下所示

      Bank       date               creationdate
0     JP Morgan  2010-07-22 2010-07-22 12:17:38.187000
1     JP Morgan  2010-07-31 2010-07-31 12:41:57.083000
2     JP Morgan  2010-11-18 2010-11-18 19:24:15.503000
3     JP Morgan  2011-03-08 2011-03-08 18:57:31.477000
4     JP Morgan  2011-04-27 2011-04-27 13:13:01.357000
5     JP Morgan  2011-05-01 2011-05-01 17:19:28.773000
6     JP Morgan  2011-05-06 2011-05-06 19:40:51.757000
7     JP Morgan  2011-05-10 2011-05-10 01:14:52.503000
8     JP Morgan  2011-05-23 2011-05-23 20:36:18.490000
9     JP Morgan  2011-05-25 2011-05-25 15:51:08.650000
10    JP Morgan  2011-05-28 2011-05-28 21:08:30.270000
11    JP Morgan  2011-05-29 2011-05-29 04:18:26.693000
12    JP Morgan  2011-06-03 2011-06-03 16:54:13.770000
13    JP Morgan  2011-06-08 2011-06-08 18:35:50.450000
14    JP Morgan  2011-06-08 2011-06-08 18:37:12.493000
15    JP Morgan  2011-06-08 2011-06-08 18:37:45.593000

我想找出每个日期的创建日期差异的平均值。为此我正在做一个groupby并调用diff然后在分组数据上表示

df_grouped = date_df.groupby(['bank', 'date'], as_index = False)
mean = df_grouped['creationdate'].diff().mean()

但是这给了我所有差异的平均值,而不是给出与每个日期对应的差异的平均值。

请建议我如何实现每个日期的差异均值

1 个答案:

答案 0 :(得分:3)

我认为你可以一步完成.aggregate,而不是试图分两步完成:

In [30]:

print df_grouped['creationdate'].aggregate(lambda x: (np.diff(x)).mean())
         Bank       date    creationdate
0   JP Morgan 2010-07-22             NaT
1   JP Morgan 2010-07-31             NaT
2   JP Morgan 2010-11-18             NaT
3   JP Morgan 2011-03-08             NaT
4   JP Morgan 2011-04-27             NaT
5   JP Morgan 2011-05-01             NaT
6   JP Morgan 2011-05-06             NaT
7   JP Morgan 2011-05-10             NaT
8   JP Morgan 2011-05-23             NaT
9   JP Morgan 2011-05-25             NaT
10  JP Morgan 2011-05-28             NaT
11  JP Morgan 2011-05-29             NaT
12  JP Morgan 2011-06-03             NaT
13  JP Morgan 2011-06-08 00:00:57.571500

在您展示的示例数据中,只有2011-06-08有多个值,并且会产生NaT以外的数字