Srikanth Varma
Srikanth Varma

Reputation: 175

Fill columns based on the last value of another column in a pandas dataframe

I have a dataframe:

   | col_1 | col_2
---------------------
 0 | 1     | NaN
 1 | 0     | NaN
 2 | 0     | NaN
 3 | 0     | NaN
 4 | 0     | NaN
 5 | 0     | NaN
 6 | 0     | NaN
 7 | -1    | NaN
 8 | 0     | NaN
 9 | 0     | NaN
 10| 0     | NaN
 11| 0     | NaN

Now, I'm trying to populate the col_2 with either 1 or -1 based on the last occurrence of that digit in col_1.

I'm trying to get it in this format:

   | col_1 | col_2
---------------------
 0 | 1     | 1
 1 | 0     | 1
 2 | 0     | 1
 3 | 0     | 1
 4 | 0     | 1
 5 | 0     | 1
 6 | 0     | 1
 7 | -1    | -1
 8 | 0     | -1
 9 | 0     | -1
 10| 0     | -1
 11| 0     | -1

Upvotes: 0

Views: 620

Answers (1)

Erfan
Erfan

Reputation: 42946

Using replace and ffill:

df['col_2'] = df['col_1'].replace(0, np.NaN).ffill()

Output

    col_1  col_2
0       1    1.0
1       0    1.0
2       0    1.0
3       0    1.0
4       0    1.0
5       0    1.0
6       0    1.0
7      -1   -1.0
8       0   -1.0
9       0   -1.0
10      0   -1.0
11      0   -1.0

Upvotes: 2

Related Questions