1

Let's say I have the dataframe below:

my_df = pd.DataFrame({'A': [1, 2, 3]})
my_df
    A
0   1
1   2
2   3

I want to add a column B with values X if the corresponding number in A is odd, otherwise Y. I would like to do it in this way if possible:

my_df['B'] = np.where(my_df['A'] IS ODD, 'X', 'Y')

I don't know how to check if the value is odd.

CHRD
  • 1,917
  • 1
  • 15
  • 38

1 Answers1

4

You were so close!

my_df['b'] = np.where(my_df['A'] % 2 != 0, 'X', 'Y')

value % 2 != 0 will check if a number is odd. Where are value % 2 == 0 will check for evens.

Output:

   A  b
0  1  X
1  2  Y
2  3  X
PacketLoss
  • 5,561
  • 1
  • 9
  • 27