0

I want to create a new column based on the values of an existing column as follows:

import pandas as pd
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3]})

df['new_col'] = df[['col_1']].apply(lambda x: -1 if x==0 else 1, axis = 1)

This produces the error: ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0')

Using a.item() works:

df['new_col'] = df[['col_1']].apply(lambda x: -1 if x.item()==0 else 1, axis = 1)
df
  ID  col_1  new_col
0  1      0       -1
1  2      2        1
2  3      3        1

However, 'item' has been deprecated. Is there a better way to code the lambda function here?

Garry
  • 179
  • 13
  • 1
    Use `df['new_col'] = np.where(df['col_1'].eq(0), -1, 1)`, no need for custom `lambda` function, which are slow compared to native pandas/numpy methods – Erfan Oct 03 '19 at 10:35
  • Thanks, but this one doesn't work where I need to do something like ```df['new_col'] = np.where(df['col_1'].eq(0), -1, df['col_1'][0:2])``` – Garry Oct 03 '19 at 15:10

1 Answers1

1

you can try this:

df['new_col'] = df.apply(lambda x: -1 if x.col_1==0 else 1, axis = 1)
SM Abu Taher Asif
  • 2,221
  • 1
  • 12
  • 14
  • Works straight out of the box, and deals with ```df['new_col'] = df.apply(lambda x: -1 if x.col_1==0 else x.col_1[0:2], axis = 1)``` – Garry Oct 03 '19 at 15:16