error when create a simple conditional statement in Python node

I am trying to figure out the basic usage of the Python script nodes.
I want to do a basic If Else condition and every time I do it, it fails.
There is no good information on how to use this node. Clearly you cant write python code in the normal way you would in other IDE’s.
please can someone advise on what I’m doing wrong?

my basic code is below (input consists of a few columns, one of which is ClientNo. All I want to do is if a field equals ‘T’ then add a word to a new column:

import numpy as np
from pandas import DataFrame
mydata = input_table.copy()

if input_table[‘ClientNo’] == ‘T’:
mydata[‘column’] = ‘hello world’
mydata[‘column’] = 'no T ’

output_table = mydata

When I run this I get :
Traceback (most recent call last):
File “C:\Program Files\KNIME\plugins\org.knime.python2_3.6.2.v201811051558\py\”, line 278, in execute
exec(source_code, self._exec_env, self._exec_env)
File “”, line 6, in
File “C:\ProgramData\Anaconda3\envs\py37_knime\lib\site-packages\pandas\core\”, line 1576, in nonzero
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Well strictly speaking this is not a KNIME question but since we are at it (doing some more Python lately).

Here is a variant with a quick lambda function

import numpy as np
from pandas import DataFrame
mydata = input_table.copy()


mydata['column'] = mydata['ClientNo'].apply(lambda x: 'hello world' if x =='T'  else 'no T')

output_table = mydata

Two more variants including a third condition is in the KNIME workflow:

As an additional service since you might want to do more with KNIME and Python here is a basic example of the three main Python inputs and outputs between KNIME and Python, data (you already used that), graphics and prediction models (strictly speaking this pickle thing could also be done by simple Python node but it looks more KNIMEy that way :slight_smile: )

kn_example_python_if_then.knwf (22.2 KB)


awesome! thank you so much.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.