根据熊猫当前值填充先前的值序列

时间:2018-10-01 20:05:04

标签: python algorithm pandas dataframe

我有一个熊猫数据框,如下所示:

ID   Value
1      2
2      6
3      3
4      5

我想要一个提供

的新数据框

ID Value 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

任何建议都将不胜感激。

3 个答案:

答案 0 :(得分:3)

reindexrepeatcumcount结合使用以获取新值

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

答案 1 :(得分:2)

尝试

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

答案 2 :(得分:2)

使用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    
相关问题