Home > database >  Python new columns resulting from if statement
Python new columns resulting from if statement

Time:02-02

Result: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I have a dataframe

abcd = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]]),columns=['a', 'b', 'c'])

I want to create a new column "d" in this data frame where: if column c = 0, then its value is column a column b, if column c is between 1 and 3, then its value is column a and else its value is 10

My code:

if (abcd.c == 0):
   abcd.d = abcd.a   abcd.b
elif abcd.c in range (0,4):
   abcd.d = abcd.a
else:
   abcd.d = 10

Result: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

CodePudding user response:

Use numpy.select with Series.isin for test membership:

abcd['d'] = np.select([abcd.c == 0, abcd.c.isin(range (0,4))], 
                      [abcd.a   abcd.b, abcd.a], 
                      default=10)
  • Related