Python 3.x 基于另一列的列中的增量值(熊猫)

Python 3.x 基于另一列的列中的增量值(熊猫),python-3.x,pandas,dataframe,group-by,increment,Python 3.x,Pandas,Dataframe,Group By,Increment,我有DataFrame包含三列: 增量导师 增加的 其他 我想以一种特殊的方式延长数据帧。在每一行中,我想添加一些行,具体取决于incrementor,在这些行中,我们增加增量,而“其他”只是复制 我举了一个小例子,让它更清楚: df = pd.DataFrame([[2,1,3], [5,20,0], ['a','b','c']]).transpose() df.columns = ['incrementor', 'incremented', 'other'] df incremento

我有
DataFrame
包含三列:

  • 增量导师
  • 增加的
  • 其他
  • 我想以一种特殊的方式延长数据帧。在每一行中,我想添加一些行,具体取决于incrementor,在这些行中,我们增加增量,而“其他”只是复制

    我举了一个小例子,让它更清楚:

    df = pd.DataFrame([[2,1,3], [5,20,0], ['a','b','c']]).transpose()
    df.columns = ['incrementor', 'incremented', 'other']
    
    df
      incrementor incremented other
    0           2           5     a
    1           1          20     b
    2           3           0     c
    
    所需输出为:

      incrementor incremented other
    0           2           5     a
    1           2           6     a
    2           1           20    b
    3           3           0     c
    4           3           1     c
    5           3           2     c
    

    有没有一种方法可以优雅而有效地对待熊猫?还是没有办法避免循环?

    首先使用
    repeat
    incrementor
    上获取重复行

    In [1029]: dff = df.loc[df.index.repeat(df.incrementor.astype(int))]
    
    然后,使用
    cumcount

    In [1030]: dff.assign(
                  incremented=dff.incremented + dff.groupby(level=0).incremented.cumcount()
                  ).reset_index(drop=True)
    Out[1030]:
      incrementor incremented other
    0           2           5     a
    1           2           6     a
    2           1          20     b
    3           3           0     c
    4           3           1     c
    5           3           2     c
    

    细节

    In [1031]: dff
    Out[1031]:
      incrementor incremented other
    0           2           5     a
    0           2           5     a
    1           1          20     b
    2           3           0     c
    2           3           0     c
    2           3           0     c
    
    In [1032]: dff.groupby(level=0).incremented.cumcount()
    Out[1032]:
    0    0
    0    1
    1    0
    2    0
    2    1
    2    2
    dtype: int64
    

    好的,你能一步一步地看一下吗?我不知道你想做什么。