根据 table 中的标准复制数据框中的行

Duplicate rows in a dataframe according to a criterion from the table

我有这样一个数据框:

d = {'col1': ['a', 'b'], 'col2': [2, 4]}
df = pd.DataFrame(data=d)
df

>>      col1    col2
    0    a        2
    1    b        4

我想通过 col2 复制行并得到这样的 table:

>>    col1    col2
   0   a        2
   1   a        2
   2   b        4
   3   b        4
   4   b        4
   5   b        4

感谢大家的帮助!

这是我使用一些 numpy 的解决方案:

numRows = np.sum(df.col2)
blankSpace = np.zeros(numRows,).astype(str)
d2 = {'col1': blankSpace, 'col2': blankSpace}
df2 = pd.DataFrame(data=d2)

counter = 0
for i in range(df.shape[0]):
    letter = df.col1[i]
    numRowsForLetter = df.col2[i]
    
    for j in range(numRowsForLetter):
        df2.at[counter, 'col1'] = letter
        df2.at[counter, 'col2'] = numRowsForLetter
        counter += 1

df2 是你的输出数据框!