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>

<pre><code># make a column that is 0 on the first occurrence of a number in a and 1 after
df['is_duplicated'] = df.duplicated(['a']).astype(int)

# group by values of a and get the cumulative sum of duplicates
# add one since the first duplicate has a value of 0
df['b'] = df[['a', 'is_duplicated']].groupby(['a']).cumsum() + 1
</code></pre>

python pandas numpy dataframe