Home > OS >  Add row duplicated for a value missed in a Series
Add row duplicated for a value missed in a Series

Time:12-13

I want to add a row that is a duplicate of the previous one for a missed value

df = pd.DataFrame({'A':[0,1,2,3,5,6,7], 'B':['green','red','blue','blue','black','white','green']})

In this case the missed value in A column is 4 so I want add row with value 4 in column A and blue in column B because is the value of the previuos row

Desired Output


    A   B
0   0   green
1   1   red
2   2   blue
3   3   blue
4   4   blue
5   5   black
6   6   white
7   7   green

CodePudding user response:

Use A as a temporary index to reindex:

out = (df.set_index('A')
         .reindex(range(df['A'].min(), df['A'].max() 1), method='ffill')
         .reset_index()
      )

Output:

   A      B
0  0  green
1  1    red
2  2   blue
3  3   blue
4  4   blue
5  5  black
6  6  white
7  7  green
  • Related