且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将函数应用于可返回多行的pandas DataFrame

更新时间:2021-09-09 20:57:22

您可以使用groupby:

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)

所以你得到

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