0

I have a dataset and I would like to create a new column where the value of this new column is equal to the value of the previous row.

What I have:

col_a col_b
x 189
y 33
z 0
k 837
H 33

What I am looking for:

col_a col_b new_col
x 189 189
y 33 189
z 0 33
k 837 0
H 86 837

It is something very similar to what df = df.fillna(method='ffill') does, but it is not working for what I need.

user14738548
  • 167
  • 1
  • 1
  • 7

1 Answers1

0

use shift in creating a col_c and then ffill to update the missing values from col_b

df['col_c'] = df['col_b'].shift(1)
df.fillna(method='ffill', axis=1) 
    col_a   col_b   col_c
0       x   189     189
1       y   33      189
2       z   0        33
3       k   837       0
4       H   33      837
Naveed
  • 11,495
  • 2
  • 14
  • 21