very simple one and despite several google searches I could not find an answer (somewhat Python newbie). I would like to assign either 1 or 0 to a panda data frame depending on some variable. here is the pseudo code:
variable = 5
df['column name'] = if variable == 5 then 1 else 0
any pointer very much welcome thanks.
this would work but feels a bit long wounded?:
if a == 5:
df['column name'] = 1
else:
df['column name'] = 0
CodePudding user response:
You can directly convert the boolean to integer and assign it as the column value
df['column name'] = int(variable==5)
Above works for the specific case, but you can have conditional expression as well:
df['column name'] = X if variable == 5 else Y
where X is the value for True, and Y is value for False