Как установить значения столбца DataFrame условно без al oop in Python - PullRequest
2 голосов
/ 06 августа 2020

У меня есть следующий Pandas DataFrame:

enter image description here

(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:

  • If col1 > col2, value of col3 will be set to 0 on that row.
  • If col1 == col2, value of col3 will be set to 1 on that row.
  • If col1 < col2, value of col3 will be set to 2 on that row.

The above DataFrame will look as the following after this operation:

введите описание изображения здесь

Есть ли способ сделать это без цикла через DataFrame?

Ответы [ 2 ]

1 голос
/ 06 августа 2020

Мы можем сделать sign от numpy

df['col3']=np.sign((df.col2-df.col1))+1
1 голос
/ 06 августа 2020

Вы можете сделать np.select:

df['col3'] = np.select((df['col1'] > df['col2'], df['col1'] < df['col2']),
                       (0, 2), 1)

Или использовать np.sign:

df['col3'] = np.sign(df['col2']-df['col1']) + 1
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...