Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

np.where: "SyntaxError: keyword can't be an expression"

Tags:

python

I am trying to incorporate the following logic

In Column A, where column B = Stack then Column A * 100 otherwise keep column A as-is.

df['Value'] = np.where(df['columnB'] = 'Stack', df['Value'] * 100)

why am I getting a SyntaxError: keyword can't be an expression here?

like image 842
excelguy Avatar asked Apr 26 '26 02:04

excelguy


1 Answers

You must supply a condition and two outcomes for the binary condition

Without knowing much about you dataframe I believe you should be doing something like the following:

df['Value'] = np.where(df['columnB'] == 'Stack', df['columnA']*100, df['Value'])

This is because in the documentation it states:

numpy.where(condition[, x, y])
    Return elements chosen from x or y depending on condition.

Parameters: 
    condition : array_like, bool
    Where True, yield x, otherwise yield y.

So df['Value'] would be populated with columnA times 100 if columnB is 'Stack', otherwise, it keeps the value that is stored at Value

like image 113
Nathan McCoy Avatar answered Apr 27 '26 16:04

Nathan McCoy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!