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))
CodePudding user response:
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