Apply function to pandas DataFrame that can return multiple rows

后端 未结 5 1329
轮回少年
轮回少年 2020-12-03 01:37

I am trying to transform DataFrame, such that some of the rows will be replicated a given number of times. For example:

df = pd.DataFrame({\'class\': [\'A\',         


        
5条回答
  •  无人及你
    2020-12-03 02:26

    You could use groupby:

    def f(group):
        row = group.irow(0)
        return DataFrame({'class': [row['class']] * row['count']})
    df.groupby('class', group_keys=False).apply(f)
    

    so you get

    In [25]: df.groupby('class', group_keys=False).apply(f)
    Out[25]: 
      class
    0     A
    0     C
    1     C
    

    You can fix the index of the result however you like

提交回复
热议问题