How to groupby and assign an array to a column in python-pandas?
<p>Given a data frame <code>df</code> like that:</p>

<pre><code>a     b    
2     nan
3     nan
3     nan
4     nan
4     nan
4     nan 
5     nan
5     nan 
5     nan
5     nan
...
</code></pre>

<p>A critical rule is that each number <code>n</code> in <code>a</code> repeat <code>n-1</code> rows. And my expected output is:</p>

<pre><code>a     b    
2     1
3     1
3     2
4     1
4     2
4     3
5     1
5     2
5     3
5     4
...
</code></pre>

<p>Thus the number <code>m</code> in <code>b</code> is a list from <code>1</code> to <code>n-1</code>. I tried it in this way:</p>

<pre><code>df.groupby('a').apply(lambda x: np.asarray(range(x['a'].unique()[0]))) 
</code></pre>

<p>But the result is a list in one row, which is not what I want.</p>

<p>Could you please tell me how to implement it? Thanks in advance!</p>

<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a>:</p>

<pre><code>df['b'] = df.groupby('a').cumcount() + 1
print (df)
   a  b
0  2  1
1  3  1
2  3  2
3  4  1
4  4  2
5  4  3
6  5  1
7  5  2
8  5  3
9  5  4
</code></pre>

python pandas numpy dataframe