Feel like I\'ve looked just about everywhere and I know its probably something very simple. I\'m working with a pandas dataframe and looking to fill/replace data in one of
Here's a kind of brute-force method. There is probably something more elegant, but you could explicitly loop over the rows like this:
df = pd.DataFrame([0, -1, -1, -1, 0 , 0, 0, 1, 0])
df.columns = ['A']
df['B'] = df['A']
# loop here
for i in range(1,len(df)):
if df.A[i] == 0 and df.B[i-1] == -1:
df.B[i] = -1
else:
df.B[i] = df.A[i]
This gives you the result you seek:
>>> df['B']
0 0
1 -1
2 -1
3 -1
4 -1
5 -1
6 -1
7 1
8 0
using Where
df['B'] = df.A[0:len(df.A)-1].where((df.A==0 ) & (df.B.shift(-1)==-1),-1)
df['B'] = df['B'].fillna(df.A)