Home > OS >  IF(A2>A3, 1, 0) Excel formula in Pandas
IF(A2>A3, 1, 0) Excel formula in Pandas

Time:02-11

I am trying to create a column with zeros and ones based on values from 1st column. If the value of upper cell is bigger, then write 1, else 0. Example code would look like this:

df = pd.Dataframe({'col1': [1, 2, 1, 3, 0]})
df['col2'] =  ...python version of excel formula IF(A2>A3, 1, 0)...

expected output:

enter image description here

I have tried:

while True:
    for index, rows in df.iterrows():
        df['col1'] = np.where(df['col1'] > df['col1'][index 1], 1, 0)

but this is very slow and gives wrong results. Thanks in advance!

CodePudding user response:

You can use

df['col2'] = df['col1'].shift().lt(df['col1']).astype(int)

CodePudding user response:

df['col2] = (df['col1'<df['col1'].shift()).astype(int).shift(periods=-1).fillna(0)
  • Related