split item to rows pandas

Viewed 185

I have the data in dataframes like below. I want to split the item into same number of rows

>>> df
idx  a  
0  3  
1  5  
2  4 

from above dataframe, I want the below as

>>> df
idx  a  
0  1  
1  2  
2  3
3  1
4  2
5  3
6  4
7  5
8  1
9  2
10  3
11  4  

I tried several ways, but no success.

4 Answers

Here is a way with series.repeat +Groupby. cumcount assuming idx is the index- if not df.set_index('idx')['a']..rest of the code..

(df['a'].repeat(df['a']).groupby(level=0).cumcount().add(1)
        .reset_index(drop=True).rename_axis('idx'))

idx

0     1
1     2
2     3
3     1
4     2
5     3
6     4
7     5
8     1
9     2
10    3
11    4
dtype: int64

A Fun way

df.a.map(range).explode()+1 # may add reset_index(), however, I think keep the original index is good, and help us convert back.
Out[158]: 
idx
0    1
0    2
0    3
1    1
1    2
1    3
1    4
1    5
2    1
2    2
2    3
2    4
Name: a, dtype: object

Here's a numpy based one:

a = (np.arange(df.a.max())+1)
m = a <= df.a.values[:,None]
df = pd.DataFrame(m.cumsum(1)[m], columns=['a'])

print(df)

    a
0   1
1   2
2   3
3   1
4   2
5   3
6   4
7   5
8   1
9   2
10  3
11  4

List Comprehension

pd.DataFrame({'a': [x + 1 for y in df['a'] for x in range(y)]})

    a
0   1
1   2
2   3
3   1
4   2
5   3
6   4
7   5
8   1
9   2
10  3
11  4
Related