Python 基于当前值填充序列中的先前值
我有一个熊猫数据框,如下所示:Python 基于当前值填充序列中的先前值,python,algorithm,pandas,dataframe,Python,Algorithm,Pandas,Dataframe,我有一个熊猫数据框,如下所示: ID Value 1 2 2 6 3 3 4 5 我想要一个新的数据帧 ID值 1 0 1 1 1 2 2 0 2 1 2 2 2 3 2 4 2 5 2 6 3 1 3 2 3 3 3 4 任何形式的建议都将不胜感激。试试看 new_df = df.groupby('ID').
ID Value
1 2
2 6
3 3
4 5
我想要一个新的数据帧
ID值
1 0
1 1
1 2
2 0
2 1
2 2
2 3
2 4
2 5
2 6
3 1
3 2
3 3
3 4
任何形式的建议都将不胜感激。试试看
new_df = df.groupby('ID').Value.apply(lambda x: pd.Series(np.arange(x+1)))\
.reset_index().drop('level_1', 1)
ID Value
0 1 0
1 1 1
2 1 2
3 2 0
4 2 1
5 2 2
6 2 3
7 2 4
8 2 5
9 2 6
10 3 0
11 3 1
12 3 2
13 3 3
14 4 0
15 4 1
16 4 2
17 4 3
18 4 4
19 4 5
使用
reindex
和repeat
和cumcount
更新新值
df.reindex(df.index.repeat(df.Value+1)).assign(Value=lambda x : x.groupby('ID').cumcount())
Out[611]:
ID Value
0 1 0
0 1 1
0 1 2
1 2 0
1 2 1
1 2 2
1 2 3
1 2 4
1 2 5
1 2 6
2 3 0
2 3 1
2 3 2
2 3 3
3 4 0
3 4 1
3 4 2
3 4 3
3 4 4
3 4 5
使用
stack
和列表理解:
vals = [np.arange(i+1) for i in df.Value]
(pd.DataFrame(vals, index=df.ID)
.stack().reset_index(1, drop=True).astype(int).to_frame('Value'))
Value
ID
1 0
1 1
1 2
2 0
2 1
2 2
2 3
2 4
2 5
2 6
3 0
3 1
3 2
3 3
4 0
4 1
4 2
4 3
4 4
4 5