У меня есть следующий 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:
введите описание изображения здесь
Есть ли способ сделать это без цикла через DataFrame?
Мы можем сделать sign от numpy
sign
numpy
df['col3']=np.sign((df.col2-df.col1))+1
Вы можете сделать np.select:
np.select
df['col3'] = np.select((df['col1'] > df['col2'], df['col1'] < df['col2']), (0, 2), 1)
Или использовать np.sign:
np.sign
df['col3'] = np.sign(df['col2']-df['col1']) + 1