2017-08-17 13 views
0

私はこのようになり、Pythonのパンダのデータフレームを有する:グループ化し、割り当てる繰り返し数(第一、第二、第三の)

date userid 
2017-03 a 
2017-04 b 
2017-06 b 
2017-08 b 
2017-05 c 
2017-08 c 

Iの回数を示す第3の列を作成したいと考えています

date userid repetition 
2017-03 a 1 
2017-04 b 1 
2017-06 b 2 
2017-08 b 3 
2017-05 c 1 
2017-08 c 2 

はこれまでのところ、私はユーザーIDと日付で、それをグループ化されたが、私は唯一の総カウント

data['newcol'] = data.groupby(['sampleid'])['date'].transform('count') 
0123を取得する方法を見つけました:フレームは次のようになりますので、サンプルは、その日に繰り返しました。

ありがとうございます!

答えて

1

使用cumcount

In [282]: df.groupby('userid').cumcount().add(1) 
Out[282]: 
0 1 
1 1 
2 2 
3 3 
4 1 
5 2 
dtype: int64 

In [283]: df.assign(repetition=df.groupby('userid').cumcount().add(1)) 
Out[283]: 
     date userid repetition 
0 2017-03  a   1 
1 2017-04  b   1 
2 2017-06  b   2 
3 2017-08  b   3 
4 2017-05  c   1 
5 2017-08  c   2 

それとも、あなたは私が問題を書くよりも速くした

In [285]: df['repetition'] = df.groupby('userid').cumcount().add(1) 

In [286]: df 
Out[286]: 
     date userid repetition 
0 2017-03  a   1 
1 2017-04  b   1 
2 2017-06  b   2 
3 2017-08  b   3 
4 2017-05  c   1 
5 2017-08  c   2 
+0

を割り当てます!どうもありがとうございます! – PatVW

関連する問題