2017-09-09 12 views
1

IはDataFrame含む3つの列た:インクリメント値(パンダ)

  1. インクリメンタ
  2. インクリメント
  3. 他I希望

長く特定の方法でDataFrame。各行では、インクリメンタに応じていくつかの行を追加したいが、これらの行ではインクリメントされたインクリメントをインクリメントし、「その他」は単にレプリケートされる。

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 

あり

は、私はそれがより明確になり、小さな例を作ったのですか?または、ループを回避する方法はありませんか?

+0

さて、あなたはそれを歩いて歩くことができますか?私はあなたが何をしたいのか分かりません。 – MSeifert

答えて

1

まず、次にrepeat.loc

In [1029]: dff = df.loc[df.index.repeat(df.incrementor.astype(int))] 

を使用してincrementorに繰り返し行を取得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 
incrementedを変更します
関連する問題