根据子组统计熊猫数据框中每年的发生次数


问题内容

想象一个pandas

df = pd.DataFrame({
    'id': [1, 1, 1, 2, 2],
    'location': [1, 2, 3, 1, 2],
    'date': [pd.to_datetime('01-01-{}'.format(year)) for year in [2015, 2016, 2015, 2017, 2018]]
}).set_index('id')

看起来像这样

    location       date
id                     
1          1 2015-01-01
1          2 2016-01-01
1          3 2015-01-01
2          1 2017-01-01
2          2 2018-01-01

现在,我想为该date列中代表的每一年创建一个列,将发生次数计数为id。因此,结果数据帧应如下所示

    location       date  2015  2016  2017  2018
id                                             
1          1 2015-01-01     2     1     0     0
1          2 2016-01-01     2     1     0     0
1          3 2015-01-01     2     1     0     0
2          1 2017-01-01     0     0     1     1
2          2 2018-01-01     0     0     1     1

现在我可以想象使用,pd.groupby.transform但是我找不到最佳的解决方案。


我自己的解决方案是

df['year'] = df['date'].map(lambda x: x.year)
df = pd.merge(
    df, 
    pd.pivot_table(df, 'date', 'id', 'year', 'count').fillna(0).astype(int), 
    left_index=True, right_index=True).drop('year', axis=1)

问题答案:

get_dummies

df.join(pd.get_dummies(df.date.dt.year).sum(level=0))

         date  location  2015  2016  2017  2018
id                                             
1  2015-01-01         1     2     1     0     0
1  2016-01-01         2     2     1     0     0
1  2015-01-01         3     2     1     0     0
2  2017-01-01         1     0     0     1     1
2  2018-01-01         2     0     0     1     1

factorize

i, r = pd.factorize(df.index)
j, c = pd.factorize(df.date.dt.year)
n, m = shape = len(r), len(c)
b = np.zeros(shape, dtype=np.int64)
np.add.at(b, (i, j), 1)

df.join(pd.DataFrame(b, r, c).rename_axis('id'))

         date  location  2015  2016  2017  2018
id                                             
1  2015-01-01         1     2     1     0     0
1  2016-01-01         2     2     1     0     0
1  2015-01-01         3     2     1     0     0
2  2017-01-01         1     0     0     1     1
2  2018-01-01         2     0     0     1     1