基于另一列(Pandas)增加列中的值

时间:2017-09-09 17:56:43

标签: python-3.x pandas dataframe group-by increment

我的DataFrame包含三列:

  1. 增量器
  2. 递增
  3. 其他
  4. 我想以特定方式延长DataFrame。在每一行中,我想添加一些行,具体取决于增量器,在这些行中,我们递增递增,而“other”只是复制。

    我做了一个小例子,让它更清晰:

    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
    

    Pandas有没有办法优雅高效地完成这项工作?或者没有办法避免循环?

1 个答案:

答案 0 :(得分:1)

首先使用incrementorrepeat

.loc上获取重复的行
In [1029]: dff = df.loc[df.index.repeat(df.incrementor.astype(int))]

然后,使用incremented

修改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