How to duplicate rows based on a counter column

孤人 提交于 2020-01-10 02:07:41

问题


Let's say I have a data frame called df

x count 
d 2
e 3
f 2

Count would be the counter column and the # times I want it to repeat.

How would I expand it to make it

x count
d 2
d 2
e 3
e 3
e 3
f 2
f 2

I've already tried numpy.repeat(df,df.iloc['count']) and it errors out


回答1:


You can use np.repeat()

import pandas as pd
import numpy as np

# your data
# ========================
df

   x  count
0  d      2
1  e      3
2  f      2

# processing
# ==================================
np.repeat(df.values, df['count'].values, axis=0)


array([['d', 2],
       ['d', 2],
       ['e', 3],
       ['e', 3],
       ['e', 3],
       ['f', 2],
       ['f', 2]], dtype=object)

pd.DataFrame(np.repeat(df.values, df['count'].values, axis=0), columns=['x', 'count'])

   x count
0  d     2
1  d     2
2  e     3
3  e     3
4  e     3
5  f     2
6  f     2



回答2:


You could use .loc with repeat like

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

Or, using pd.Series.repeat you can

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


来源:https://stackoverflow.com/questions/31485361/how-to-duplicate-rows-based-on-a-counter-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!