Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the dataframe as below:

df

ID  val

1   0.0

2   yes

3   1.0

4   0.0

5   yes

How do I match my previous value with my current value if the column val equals "yes"

I tried using the code below:

 df['val'] = df['val'].replace('yes', np.nan).bfill().astype(str) 

I am getting this output which is not what I wanted to.

ID  val

1   yes

2   yes

3   1.0

4   yes

5   yes

can we use np.where along with the bfill? 

1 Answer

0 votes
by (36.8k points)

You can use the below code:

df.loc[df['val'].shift(-1).eq('yes'), 'val'] = 'yes'

Output:

   ID  val

0   1  yes

1   2  yes

2   3  1.0

3   4  yes

4   5  yes

 If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...