Apply function to pandas DataFrame that can return multiple rows

后端 未结 5 1335
轮回少年
轮回少年 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:10

    This question is very old and the answers do not reflect pandas modern capabilities. You can use iterrows to loop over every row and then use the DataFrame constructor to create new DataFrames with the correct number of rows. Finally, use pd.concat to concatenate all the rows together.

    pd.concat([pd.DataFrame(data=[row], index=range(row['count'])) 
               for _, row in df.iterrows()], ignore_index=True)
    
      class  count
    0     A      1
    1     C      2
    2     C      2
    

    This has the benefit of working with any size DataFrame.

提交回复
热议问题