I have the following Pandas DataFrame:

(My original DataFrame is a lot bigger than the one in this example.)
I need to add another column (col3) to this DataFrame and values of col3 will be set based on following conditions:
The above DataFrame will look as the following after this operation:

Is there a way to do this without looping through the DataFrame?
We can do sign from numpy
df['col3']=np.sign((df.col2-df.col1))+1
You can do np.select:
df['col3'] = np.select((df['col1'] > df['col2'], df['col1'] < df['col2']),
(0, 2), 1)
Or use np.sign:
df['col3'] = np.sign(df['col2']-df['col1']) + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With