如何基于计数器列复制行 [英] How to duplicate rows based on a counter column
本文介绍了如何基于计数器列复制行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个名为df的数据框
Let's say I have a data frame called df
x count
d 2
e 3
f 2
Count是计数器列,是我希望重复的次数.
Count would be the counter column and the # times I want it to repeat.
我将如何扩展它来制作
x count
d 2
d 2
e 3
e 3
e 3
f 2
f 2
我已经尝试过 numpy.repeat(df,df.iloc ['count'])会出错
I've already tried numpy.repeat(df,df.iloc['count']) and it errors out
推荐答案
您可以使用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
这篇关于如何基于计数器列复制行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文