熊猫 - 按

时间:2017-03-20 08:18:45

标签: python date pandas group-by

我想将分组后的天数计算为2列:

groups = df.groupby([df.col1,df.col2])

现在我想计算每组的相关天数:

result = groups['date_time'].dt.date.nunique()

我想在白天分组时使用类似的东西,但在这里我收到了错误:

  

AttributeError:无法访问属性' dt' ' SeriesGroupBy'对象,尝试使用' apply'方法

获取天数的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

您需要groupby的另一种变体 - 首先定义列:

df['date_time'].dt.date.groupby([df.col1,df.col2]).nunique()
df.groupby(['col1','col2'])['date_time'].apply(lambda x: x.dt.date.nunique())
df['date_time1'] = df['date_time'].dt.date
a = df.groupby([df.col1,df.col2]).date_time1.nunique()

样品:

start = pd.to_datetime('2015-02-24')
rng = pd.date_range(start, periods=10, freq='15H')

df = pd.DataFrame({'date_time': rng, 'col1': [0]*5 + [1]*5, 'col2': [2]*3 + [3]*4+ [4]*3})  
print (df)
   col1  col2           date_time
0     0     2 2015-02-24 00:00:00
1     0     2 2015-02-24 15:00:00
2     0     2 2015-02-25 06:00:00
3     0     3 2015-02-25 21:00:00
4     0     3 2015-02-26 12:00:00
5     1     3 2015-02-27 03:00:00
6     1     3 2015-02-27 18:00:00
7     1     4 2015-02-28 09:00:00
8     1     4 2015-03-01 00:00:00
9     1     4 2015-03-01 15:00:00
#solution with apply
df1 = df.groupby(['col1','col2'])['date_time'].apply(lambda x: x.dt.date.nunique())
print (df1)
col1  col2
0     2       2
      3       2
1     3       1
      4       2
Name: date_time, dtype: int64

#create new helper column
df['date_time1'] = df['date_time'].dt.date
df2 = df.groupby([df.col1,df.col2]).date_time1.nunique()
print (df2)
col1  col2
0     2       2
      3       2
1     3       1
      4       2
Name: date_time, dtype: int64

df3 = df['date_time'].dt.date.groupby([df.col1,df.col2]).nunique()
print (df3)
col1  col2
0     2       2
      3       2
1     3       1
      4       2
Name: date_time, dtype: int64