Conditional replacement based on previous value in same pandas python dataframe column

I feel that I look almost everywhere, and I know that this is probably something very simple. I work with the pandas framework and want to fill / replace data in one of the columns based on the data from this TABLE. I tend to be more excel users and it is very simple in excel. If we have:

df = pd.DataFrame([0, -1, -1, -1, 0 , 0, 0, 1, 0]) df.columns = ['A'] df['B'] = df['A'] 

in excel, what I'm trying to do will be "= IF (AND (A2 = 0, B1 = -1), -1, A2) so that I can then drag the column" B ", and this applies In essence, based on the previous the data points of column B and the current value of column A, I need to update the current value of B.

I tried:

 df['B'] = np.where((df['A'] == 0), (df['B'].shift(1) == -1), df['B'].replace(to_value = 0, method = 'ffill'), df['A']) 

and many other versions of this, as well as variations of iterrows and other incredibly extreme workarounds to no avail.

Any suggestions are welcome.

EDIT:

the result will be:

 df['B'] = [0, -1, -1, -1, -1 , -1, -1, 1, 0] 
0
source share
2 answers

Here is a kind of brute force method. Something may be more elegant, but you can explicitly iterate over the lines as follows:

 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 are looking for:

 >>> df['B'] 0 0 1 -1 2 -1 3 -1 4 -1 5 -1 6 -1 7 1 8 0 
0
source

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) 
0
source

Source: https://habr.com/ru/post/1239310/


All Articles