Replicating rows in a pandas data frame by a column value

后端 未结 3 1729
北海茫月
北海茫月 2020-11-28 09:35

I want to replicate rows in a Pandas Dataframe. Each row should be repeated n times, where n is a field of each row.

import pandas as pd

what_i_have = pd.D         


        
3条回答
  •  Happy的楠姐
    2020-11-28 10:11

    Not the best solution, but I want to share this: you could also use pandas.reindex() and .repeat():

    df.reindex(df.index.repeat(df.n)).drop('n', axis=1)
    

    Output:

    
       id   v
    0   A   10
    1   B   13
    1   B   13
    2   C   8
    2   C   8
    2   C   8
    

    You can further append .reset_index(drop=True) to reset the .index.

提交回复
热议问题