Python 如何基于计数器列复制行
假设我有一个名为df的数据帧Python 如何基于计数器列复制行,python,pandas,dataframe,expand,Python,Pandas,Dataframe,Expand,假设我有一个名为df的数据帧 x count d 2 e 3 f 2 Count将是计数器列和我希望它重复的#次 我该如何扩展它使之成为现实 x count d 2 d 2 e 3 e 3 e 3 f 2 f 2 我已经试过了 numpy.repeat(df,df.iloc['count'])会出错您可以使用np.repeat() 您可以将.loc与重复一起使用 In [295]: df.loc[df.index.repeat(df['count'])].reset_index(drop=
x count
d 2
e 3
f 2
Count将是计数器列和我希望它重复的#次
我该如何扩展它使之成为现实
x count
d 2
d 2
e 3
e 3
e 3
f 2
f 2
我已经试过了
numpy.repeat(df,df.iloc['count'])会出错您可以使用
np.repeat()
您可以将.loc
与重复一起使用
In [295]: df.loc[df.index.repeat(df['count'])].reset_index(drop=True)
Out[295]:
x count
0 d 2
1 d 2
2 e 3
3 e 3
4 e 3
5 f 2
6 f 2
或者,使用pd.Series.repeat
您可以
In [278]: df.set_index('x')['count'].repeat(df['count']).reset_index()
Out[278]:
x count
0 d 2
1 d 2
2 e 3
3 e 3
4 e 3
5 f 2
6 f 2
什么是D2E3F2?它们是圆柱吗?
In [278]: df.set_index('x')['count'].repeat(df['count']).reset_index()
Out[278]:
x count
0 d 2
1 d 2
2 e 3
3 e 3
4 e 3
5 f 2
6 f 2