简体   繁体   中英

How to make current row value equal to previous row value if a column equals a value in Pandas?

I have a dataframe as below:

df

ID  val
1   0.0
2   yes
3   1.0
4   0.0
5   yes

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

I tried df['val'] = df['val'].replace('yes', np.nan).bfill().astype(str) , but wont work as desired.

desired output

ID  val
1   yes
2   yes
3   1.0
4   yes
5   yes

can we use np.where along with bfill? how to go about with this?

How about:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM