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

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!



Solution 1:[1]

Here is the final solution I came up with:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1