我有如下所示的数据格式。我想将项目分割成相同的行数。
>>> df
idx a
0 3
1 5
2 4 从上面的数据,我想要下面的
>>> 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 我试过几种方法,但都没有成功。
发布于 2020-03-18 15:20:55
有趣的方式
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发布于 2020-03-18 15:15:41
下面是一种使用series.repeat +Groupby. cumcount假设idx是索引的方法-如果不是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发布于 2020-03-18 15:24:48
下面是一个基于矮胖的视频:
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 4https://stackoverflow.com/questions/60742389
复制相似问题