我的DataFrame
包含三列:
我想以特定方式延长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有没有办法优雅高效地完成这项工作?或者没有办法避免循环?
答案 0 :(得分:1)
首先使用incrementor
和repeat
.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