Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If condition, store previous df column value, without loop

is it possible to retrieve previous column value without loop in pandas?

import pandas as pd
import numpy as np

df=pd.DataFrame({'a': [True, False, False, True, True, False], 'b': [0, 0, 0, 3, 4, 4]})

df
Out[427]: 
       a  b
0   True  0
1  False  0
2  False  0
3   True  3
4   True  4
5  False  4
If df[‘a’] = True, store index, else previous value
# Attempt 1
df['c'] = np.where(df['a'], df.index, df['c'].shift(1))


# Attempt 2
df['c'] = df.index
df['c'] = np.where(df['a'], df['c'], df['c'].shift(1))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use a ffill on the index converted to_series after masking the non-True values:

df['b'] = df.index.to_series().where(df['a']).ffill(downcast='infer')

output:

       a  b
0   True  0
1  False  0
2  False  0
3   True  3
4   True  4
5  False  4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading